让我马上说清楚,这是针对大学课程的。我不能使用 C++ 库,只能使用标准 C 库。不要建议我使用 C++ 字符串或 cin/cout,因为这对我的作业没有帮助。
我的问题:我在主函数中有全局字符数组。我需要在函数 foo() 中将字符串从 scanf() 传递给全局字符数组。一切都编译得很好,问题是 scanf() 函数似乎对它指向的全局字符数组没有影响。正如参考书所指示的那样,我正在使用“地址”运算符(&)。也许,我不了解字符数组指针和 scanf()“地址”(&) 之间的关系。我觉得我到处寻找解决方案。
我在这个问题上花了几个小时,所以我现在正在寻找专家的建议。
这是我的程序的简化版本。
#include <stdio.h>
void foo(char arr1[], char arr2[]);
int main(void)
{
char arr1[20] = "initial";
char arr2[25] = "second";
foo(arr1); // <------- should change it to the string "second" upon scanf()
printf("Test Return Value: %s\n",arr1); // <---- returns "initial" (the problem)
printf("Enter a test value: ");
scanf("%s", &arr1);
printf("Test Return Value: %s\n",&arr1);
// ---------------------- this code is not part of the issue
fflush(stdin);
getchar();
return 0;
// ----------------------
}
void foo(char arr1[], char arr2[])
{
// there will be many returned values
printf("Enter a test value: ");
scanf("%s", &arr1); // <---------- the problem function (input < 20 chars)
}