C所有值都随着指针改变

问题描述 投票:0回答:1

我正在尝试用C编写一个方法来从文件中读取。我不知道文件要多长时间,但我知道结构。问题是,当我更改str的值时,所有引用它的var都被更改了。有什么办法可以使我的var的值保持不变?抱歉,代码混乱。

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;
}
c pointers memory-management
1个回答
0
投票

您正在分配指针而不是复制内容。

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

应该是

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

注意:: strdup在内部分配内存并复制内容,因此您需要先完成free,而且strdup不是c标准。

© www.soinside.com 2019 - 2024. All rights reserved.