繁体   English   中英

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

[英]why does NULL condition terminate after 3 chars

我写了这个函数,该函数应该将一个字符串读入一个数组,直到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;
}

无论我键入多少个字符,当我打印结果时,它只会给我前3个字符,我也不知道为什么。 任何想法? 谢谢

如前所述, scanf不会为您的字符串以空值终止。 如果您要阅读直到用户按下回车键,请进行检查。 您可以通过以下方式将for循环替换为do-while循环:

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调用之前检查的,这意味着循环条件只是检查旧的垃圾数据(而不是正确的值)。

问题出在你的循环中

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';

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM