gpt4 book ai didi

c - 指向字符的指针

转载 作者:太空宇宙 更新时间:2023-11-04 05:19:40 25 4
gpt4 key购买 nike

这是一个片段:

void addproductInterface(Tsklep **head){
char* name = (char*)malloc(sizeof(char)*100);
double price;
do{
printf("Name: ");
scanf("%s[^\n]", name);
fflush(stdin);
printf("\nPrice: ");
scanf("%lf", &price);
fflush(stdin);
addProduct(&(*head), name, price);
} while(prompt("Do you want to add another one?"));

它有效,但在我添加另一个 产品后,它会将之前的(和以前的)更改为这个名称。看起来,我每次都传递相同的指针,我只是更改它指向的数组(当我添加另一个产品时)。我理解正确吗?您有解决方法吗?

最佳答案

听起来像您描述的那样,是的。如果没有看到 addProduct() 的代码,很难确定,但那将是分配新内存的地方。

您应该为输入使用临时的、自动的(在堆栈上)缓冲区,然后在存储记录时在 addProduct() 中进行永久分配:

do{
char name[64];
double price;

printf("Name: ");
scanf("%63s", name);
fflush(stdin);
printf("\nPrice: ");
scanf("%lf", &price);
fflush(stdin);
addProduct(&(*head), name, price);
} while(prompt("Do you want to add another one?"));

您还应该对 scanf() 调用进行错误检查,如果给出意外输入,它们可能会失败。

此外,don't cast the return value of malloc() in C .

关于c - 指向字符的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16853637/

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