问题
I'm making a program where a teacher can enter the number of students and their full name. I don't know what I'm doing wrong because this is the first time I'm trying to print an array of strings. This is the part of my program that I'm having trouble with:
#include <stdio.h>
int main()
{
int n_students,i,b=1;
char surname[20],first_name[20];
printf("number of students:");
scanf("%d",&n_students);
for(i=0;i<n_students;i++)
{
printf("%d. ",b);
scanf("%s %s",&surname[i],&first_name[i]);
}
for(i=0;i<n_students;i++)
{
printf("%s, %s",first_name[i],surname[i]);
}
}
this part is what Im having trouble with. pls help
for(i=0;i<n_students;i++)
{
printf("%s, %s",first_name[i],surname[i]);
}
回答1:
printf("%s, %s",first_name[i],surname[i]);
invokes undefined behavior because it is passing char
where char*
is required.
You have only two strings, not array of strings.
Fixed code:
#include <stdio.h>
#define MAX_STUDENT_NUM 1024
int main(void)
{
int n_students,i,b=1;
/* allocate arrays of (arrays to store) strings */
char surname[MAX_STUDENT_NUM][20],first_name[MAX_STUDENT_NUM][20];
printf("number of students:");
/* check if scanf() is successful */
if(scanf("%d",&n_students) != 1)
{
fputs("number read failed\n", stderr);
return 1;
}
/* check the number to avoid buffer overrun */
if(n_students > (int)(sizeof(surname) / sizeof(*surname)))
{
fputs("too many students\n", stderr);
return 1;
}
for(i=0;i<n_students;i++)
{
printf("%d. ",b);
/* remove & and limit length to read to avoid buffer overrun */
/* check if scanf() is successful */
if(scanf("%19s %19s",surname[i],first_name[i]) != 2)
{
fputs("failed to read names\n", stderr);
return 1;
}
}
for(i=0;i<n_students;i++)
{
printf("%s, %s",first_name[i],surname[i]);
}
}
来源:https://stackoverflow.com/questions/65453961/array-of-strings-wont-print