C 标准库函数 'strncpy' 不工作

C standard library function 'strncpy' not working

C代码:

#include<stdio.h>
#include<string.h>

#define STRINGS 10
#define STR_LEN 20

int main(void)
{
    char words[STRINGS][STR_LEN];

    char input[STR_LEN];

    int i;
    int mycount;

    for(i = 0;i < STRINGS;++i;)
    {
        printf("Enter a word (or 0 to quit)\n:");

        scanf("%19s", input);

        if(input[0] == '0') break;

        strncpy(words[i], input, STR_LEN);

        mycount++;
    }

    printf("A total of %d strings were entered!\n",mycount);

}

问题:当我 运行 此代码并输入一些字符串时,它不会打印出我输入的字符串数量

enter image description here

您需要将计数初始化为 0。

int mycount =0;

变量mycount未初始化。然后您尝试通过 ++ 运算符在 for 循环中修改它。所以你正在读取垃圾值并写入垃圾值。这解释了您得到的输出。

读取未初始化的变量会调用 undefined behavior。在这种情况下,它表现为垃圾值,但它可以很容易地输出预期值或导致崩溃。

在声明时初始化此变量。

int mycount = 0;