gpt4 book ai didi

c - 每次迭代都会替换索引中的值

转载 作者:太空宇宙 更新时间:2023-11-04 01:34:20 24 4
gpt4 key购买 nike

我创建了一个 C 程序,我应该在其中读取一个文本文件并通过 int 和字符串指针将其分配给一个结构。

这是我的程序的代码片段:

i = 0;
while(!feof(phoneBook)) {
fscanf(phoneBook, "%d|%s\n", &num, fname);
info[i].phone_num = num;
printf("%d\n", info[i].phone_num);
info[i].first_name = fname;
printf("%s\n", info[i].first_name);

i++;
ctr++;
printf("\nfirst:%s", info[0].first_name);
printf("\nsecond:%s", info[1].first_name);
printf("\nthird:%s\n\n", info[2].first_name);
}

在第一次迭代中,它将第一行分配给 info 的 0 索引。对于第二次迭代,它将第二行分配给索引 1 并替换索引 0。

文本文件仅包含以下几行(用于测试目的):第一的第二第三名

这是输出:

//first iteration
first:first
second: <null>
third: <null>
//second
first:second
second: second
third: <null>
//third
first:third
second: third
third: third

顺便说一下,我将我的结构声明为:

typedef struct{
int id;
char *first_name;
char *last_name;
int phone_num;
} phone_det;

phoneBook 在数据类型 phone_det 下声明。

我们将不胜感激任何形式的帮助!我刚开始使用 C,我仍然对指针有点困惑。 :(

最佳答案

虽然我们看不到你的结构,你每次都分配指针到相同的名称缓冲区,并且不将名称缓冲区本身复制到特定数组,所以你最终有许多指向相同名称缓冲区的不同指针。

关于c - 每次迭代都会替换索引中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17387137/

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