这种情况往指针数组里存用户输入的字符串gets怎么用呢,或者更好的方法。
问题描述:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define N 20
int main()
{
int n,i;
printf("Please input an integer:");
scanf("%d",&n);
char (*ptr)[N]=NULL;
(char*)malloc(sizeof(char)*n);
printf("Please input %d strings:",n);
for(i=0;i<n;i++){
gets(*ptr);
}
printf("%s",&ptr[0][0]);
free(ptr);
}
答
代码修改如下:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define N 20
int main()
{
int n,i;
printf("Please input an integer:");
scanf("%d",&n);
char *ptr[N];//=NULL;
printf("Please input %d strings:",n);
for(i=0;i<n;i++){
ptr[i] = (char*)malloc(200);//200这个数根据情况调整一下大小
gets(ptr[i]);
}
//输出
for(i=0;i<n;i++)
printf("%s\n",ptr[i]);
for(i=0;i<n;i++)
{
free(ptr[i]);
ptr[i] = 0;
}
}