I am trying to get names stored in a string array as user input. When I do this, the program returns an empty element at the beginning of the array, and the last element the user inputs is not stored.
The code works if I change the condition in the for
loops to <= size
, but I still want to understand where the empty element comes from. 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;
}