【发布时间】:2015-08-28 17:50:23
【问题描述】:
我试图在一个 char 指针数组中输入多个字符串,没有。字符串也取自用户。我已经编写了以下代码,但它不能正常工作,请问有人可以帮助我修复它吗?它需要一些随机的不。用户未给出的输入。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int l,j,i=0;
int p;// scanning no of strings user wants to input
scanf("%d",&p);
char c;
char **ptr=(char**)malloc(sizeof(char*)*p);// array of char pointer
if(ptr!=NULL)
{
for(i=0;i<p;i++)//loop for p no of strings
{
j=0;
ptr[i]=(char*)malloc(200*sizeof(char));//allocating memory to pointer to char array
if(ptr[i]!=NULL)//string input procedure
{
while(1)
{
c=getchar();
if(c==EOF||c=='\n')
{
*(ptr[i]+j)='\0';
break;
}
*(ptr[i]+j)=c;
j++;
}
printf("%s \n",ptr[i]);
i++;
}
}
}
getch();
free(ptr);
return 0;
}
【问题讨论】:
-
0)
scanf("%d",&p);-->scanf("%d%*c",&p);1) 删除i++;2) 还free应用ptr[i]