gpt4 book ai didi

C 所有值都随指针改变

转载 作者:行者123 更新时间:2023-11-30 14:34:32 25 4
gpt4 key购买 nike

我正在尝试用 C 语言编写一个方法来从文件中读取数据。我不知道文件有多长,但我知道结构。问题是,当我更改 str 的值时,引用它的所有变量都会更改。有什么办法可以让我的变量的值保持不变吗?抱歉,代码很乱。

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;
}

最佳答案

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

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

应该是

       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.

关于C 所有值都随指针改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58926787/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com