我正在做C编程作业。我遇到一个问题,即用户键入scanf函数的变量总是输出相同的东西。
void Update(char mCode, int mPrice)
{
printf("Enter Code: ");
scanf("%s",&mCode);
printf("Enter Selling Price: ");
scanf("%d",&mPrice);
}
int main(void)
{
....
update(stuff[i].mCode,stuff[i].mPrice);
fp = fopen("readme.txt","a+");
fprintf(fp, "%s %d\n", stuff[i].mCode, &stuff[i].mPrice);
....
return 0;
}
我在readme.txt中得到的结果是mPrice 0,mCode 空白。
答案 0 :(得分:1)
变量mCode
和mPrice
是函数Update
中的局部变量。
因此,它们仅在此功能中本地更新。
按如下方式更改:
void Update(char* mCode, int* mPrice)
{
printf("Enter Code: ");
scanf("%s",mCode);
printf("Enter Selling Price: ");
scanf("%d",mPrice);
}
int main(void)
{
....
update(&stuff[i].mCode,&stuff[i].mPrice);
fp = fopen("readme.txt","a+");
fprintf(fp, "%s %d\n", stuff[i].mCode, &stuff[i].mPrice);
....
return 0;
}
答案 1 :(得分:0)
并不是"数组传递"不工作。您没有传递任何数组。
请注意,您对Update
的定义表示,您通过值传递mCode
和mPrice
。这意味着副本在那里制作,你将数据读入这些副本(生命在函数结束时结束)。你需要传递一个引用,如果c是一个指针。
void Update(char* mCode, int* mPrice)
{
printf("Enter Code: ");
scanf("%s",mCode); // just pass the pointer through to scanf now
printf("Enter Selling Price: ");
scanf("%d",mPrice); // just pass the pointer through to scanf now
}
int main(void)
{
....
update(&stuff[i].mCode,&stuff[i].mPrice); //pass the addresses
fp = fopen("readme.txt","a+");
fprintf(fp, "%s %d\n", stuff[i].mCode, &stuff[i].mPrice);
....
return 0;
}