二楼的修改方式可以得到正确结果,是学校里的经典方法。
动态分配内存也是可以的,但是需要注意内存资源用完了要释放:)
#include “stdio.h“
#include “string.h“
#include “alloc.h“
void main()
{
int n,i;
char s[20]=“ “;
char *str[5]={“ “,“ “ ,“ “,“ “,“ “};
printf(“\nPlease input students number:“);
scanf(“%d“,&n);
for(i=0;i
{
printf(“Please input NO for student%d:“,i+1);
fflush(stdin);
gets(s);
/*alloc mem for str[i]*/
if( NULL == (str[i] = malloc(strlen(s)+1)) )
{
printf(“\nNot enough memory to allocate buffer\n“);
for(;i<=0;i--)
{
free(str[i-1]);
}
exit(1); /* terminate program if out of memory */
}
/*Init for str[i]*/
memset(str[i], ’\0’, (strlen(s)+1));
strcpy(str[i],s);
}
for(i=0;i
{
printf(“\nThe info you input:student[%d]----NO:“,i+1);
puts(str[i]);
}
/*free mem*/
for(i=0;i
{
free(str[i]);
}
getch();
}