Jinlong Ruan
Jinlong Ruan

Reputation: 1

C all the value changes with the pointer

I am trying to write a method in C to read from a file. I don't know how long the file will be but I know the structure. The problem is that when I change the value of str, all my vars that refer to it are changed. Is there any way for me to keep the value of my vars unchanged? Sorry for the messy code.

HashMap read_Table(char* srcfilename){
    FILE* src = fopen(srcfilename, "r");
    if (src == NULL) {
        printf("READ FILE FAILED\n");
    }
    char str[256];
    if (fgets(str, 255, src) != NULL) {
    }
    fgets(str, 255, src);
   char* attribute_size = str;
    int a_size = atoi(attribute_size);
    char **outAttributes = malloc(sizeof(char *) * a_size);
    fgets(str, 255, src);
    for(int i = 0; i<a_size; i++){
        if (fgets(str,255,src) != NULL){
            outAttributes[i] = str;
        }
    }
    fgets(str, 255, src);
    //get key size:
    printf("!!!!!!\n%s", str);
    fgets(str, 255, src);
    //get key size number
    printf("!!!!!!\n%s", str);
    char* key_size = str;
    int k_size = atoi(key_size);
    if (fgets(str, 255, src) != NULL) {
        //get Key:
        printf("!!!!!!\n%s", str);
    }
    char **outKeyItem = malloc(sizeof(char *) * k_size);
    for(int i = 0; i<k_size; i++){
        if (fgets(str,255,src) != NULL){
            printf("!!!!!!\n%s", str);
            outKeyItem[i] = str;
        }
    }
    fgets(str, 255, src);
    //get Table:
    HashMap out_map = new_HashMap((void**)outAttributes, a_size ,(void**)outKeyItem, k_size);
    while (!feof(src)) {
        char** curr_tuple = malloc(sizeof(char *) * a_size);
        for(int i=0;i<a_size;i++){
            if(fgets(str, 255, src)!=NULL){
                curr_tuple[i] = str;
                printf("Tuple: %d %s",i, curr_tuple[i]);
            } else{
                break;
            }
        }
        if(feof(src)){
            break;
        }
        insert(out_map, (void**)curr_tuple);
    }

    printHashMap(out_map);
    printf("\n");
    return out_map;
}

Upvotes: 0

Views: 43

Answers (1)

kiran Biradar
kiran Biradar

Reputation: 12732

You are assigning pointer instead of copying the contents.

        outAttributes[i] = str;
        outKeyItem[i] = str;

should be

       outAttributes[i] = strdup(str); //basically malloc and strcpy
       outKeyItem[i] = strdup(str);

Note:: strdup internally allocates the memory and copies the contents thus you need to free once done also strdup is not c standard.

Upvotes: 1

Related Questions