我正在尝试将多个字符串输入到一个 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;
}
最佳答案
您的问题是您首先在 for 循环开始时递增 i
,然后在循环结束时递增,因此 两次 而不是一次。您需要删除末尾的 i++;
。
注意事项:
- don't cast the result of
malloc
- 您需要
释放
您分配的char*
(即“ptr[i]
”) - 使用
ptr[i][j] = c;
代替*(ptr[i] + j) = c;
- 尽可能限制变量的范围
- 使用
fgets
从stdin
读取
- 您的代码中可能存在缓冲区溢出;
fgets
的另一个论点
关于c - char指针数组中的多个字符串输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32276992/