2011-10-20 44 views
0

让我马上说清楚,这是一个大学课程。我不能使用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) 
} 
+0

复制代码时犯了许多错误:'arr2'从不使用,'arr'没有声明。 – Simon

回答

2
scanf("%s", &arr); // <---------- the problem function (input < 20 chars) 

应该

scanf("%s", arr); // <---------- the problem function (input < 20 chars) 

使用C IO功能的危险!

+0

抱歉没有1的arr,我以为我在发布之前解决了这个问题。谢谢。我不敢相信这很容易。 – SacWebDeveloper

+0

通过IO,犯下愚蠢的错误通常非常容易。这就是为什么我们有流库,并真正推荐使用strcpy之类的东西。好的编码器是懒惰的编码器 - 让自己变得简单! – Ayjay

0

scanf功能正确的语法是:

scanf("%s", arr); 

你只需要&操作简单变量,不能用于数组/指针。

除此之外,您将不得不纠正不当使用arr1,arr2arr。部分代码使用前两个数组,而后者的其他部分使用前两个数组。

2

虽然你已经更新句话解决我有,你可能要考虑一些观察:
1.获得scanf & printf通话摆脱&arr1之前(如Ayjay &丹尼斯提到已解决你的问题)
2.正确的参数数量未传递到函数foo(如Adrian Cornish所述)。因此代码不会编译。
3. fflush(stdin);是未定义的行为。 fflush仅适用于输出流。请不要与stdin一起使用。详情请参阅this SO question
4.如果这是一个C++源代码,请使用#include <cstdio>而不是#include <stdio.h>
请始终编译带有完整编译器警告的代码并解决所有这些问题。这是一个很好的做法。 :)
希望这有助于!