gpt4 book ai didi

c - 为什么C中的字符串数组开头存放的是一个空元素?

转载 作者:太空宇宙 更新时间:2023-11-04 03:10:37 25 4
gpt4 key购买 nike

<分区>

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

如果我更改 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;
}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com