让我马上说清楚,这是一个大学课程。我不能使用C++库,只能使用标准C库。不要建议我使用C++字符串或cin/cout,因为这对我的这个任务不会有帮助。如何通过在C++中传递地址将scanf字符串传递给全局字符数组?
我的问题:我在主函数中有全局字符数组。我需要在函数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)
}
复制代码时犯了许多错误:'arr2'从不使用,'arr'没有声明。 – Simon