为什么NULL条件在3个字符后终止

时间:2013-11-17 02:39:17

标签: c

我编写了这个函数,它应该将一个字符串读入一个数组,直到NULL char,表示该行中字符串的结尾。但它不知何故不起作用。

int main(void){
    int MAX = 39;
    char number1[MAX + 1];
    int i;

    read_array(number1, MAX);

    for(i = 0; i <= MAX; i++)
        printf("%c", number1[i]);

    return 0;
}

int read_array(char* number, int size) {
    printf("\nEnter an integer number at a maximum of 39 digits please.\n");

    int result = 0;
    char* i;
    for (i = number; *i != NULL; i++)
        scanf("%c", i);

    return result;
}

无论我输入多少个字符,因为我打印结果它只给我前三个字符,我不明白为什么。任何的想法? THX

2 个答案:

答案 0 :(得分:1)

正如我之前所说,scanf不会为您终止字符串。如果您想要在用户点击进入/返回之前阅读,请检查。您可以通过使用此do-while循环替换for循环来实现此目的:

do {
    scanf("%c", i); // read the data into i *before* the loop condition check
} while (*i++ != '\n'); // check for '\n' (unless you expect the user to
                        // actually type the null character)

关于i指向垃圾内存的@NedStark点是正确的。 number1中的数据永远不会被初始化,所以它只是填充了垃圾。在 *i != NULL调用之前,检查了你的循环条件(scanf),这意味着循环条件只是检查旧的垃圾数据(而不是正确的值)。

答案 1 :(得分:0)

问题出在你的循环中

for (i = number; *i != NULL; i++)
    scanf("%c", i);

在递增i之后,i指向包含垃圾数据的下一个内存位置,因为它 尚未正确初始化。可能你想要像:

char c;
i = number;
do
{
    scanf("%c", &c);
    *i = c;
    ++i;
} while (c!='\n')
*i = '\0';