为什么C中的字符串数组在开始时存储一个空元素?

时间:2019-06-24 14:27:42

标签: c arrays string input element

我正在尝试获取存储在字符串数组中的名称作为用户输入。当我这样做时,程序将在数组的开头返回一个空元素,并且不会存储用户输入的最后一个元素。

如果我将for循环中的条件更改为<= size,则代码可以工作,但是我仍然想了解空元素的来源。 This is what I get when I run the code

#define MAXNAME 81

int main() {
    int size, i;

    printf("Input the number of names in the array: ");
    scanf("%d", &size);
    // we scan the elements to be stored in the array
    printf("Enter %d names to the array:\n", size);
    char names[size][MAXNAME];
    for (i = 0; i < size; i++) {
        gets(names[i]);
    }
    printf("\n");
    // we print the elements stored in the array
    int p;
    printf("The elements in the array are:\n");
    for (p = 0; p < size; p++) {
        printf("names[%d] = %s\n", p, names[p]);
    }
    printf("\n");
    // we search for the max length of the elements in the array
    int maxLength = 0;
    int j, k;
    for (j = 0; j < size; j++) {
        int testLength = strlen(names[j]);
        printf("The length of %s is %d\n", names[j], testLength);
        if (testLength > maxLength) {
            maxLength = testLength;
        }
    }
    printf("\n");
    printf("The maximum length is %d\n", maxLength);
    // we print the elements with size == max length
    printf("The element(s) with this length is(are):\n");
    for (k = 0; k < size; k++) {
        int compareLength = strlen(names[k]);
        if (compareLength == maxLength) {
            printf("%s\n", names[k]);
        }
    }
    return 0;
}

1 个答案:

答案 0 :(得分:1)

在此代码中,store.dispatch({ type: 'ADD_TODO', text: 'Understand the middleware' }) 读取一个整数,并在缓冲区中保留换行符。因此scanf()仅读取换行符。 我们可以通过在gets()之后添加getchar()来读取额外的换行符来解决此问题。

有关更多信息,请参见GeeksforGeeks article

更新的代码:

scanf()