char指针数组中的多个字符串输入

multiple string input in an array of char pointer

我正在尝试将多个字符串输入到一个字符指针数组中,没有。字符串也取自用户。我写了下面的代码,但它不能正常工作,请问有人能帮我解决吗?它需要一些随机编号。用户未提供的输入。

#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)='[=10=]';
            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
  • 您需要 free 您分配的 char*(即“ptr[i]”)
  • 使用ptr[i][j] = c;代替*(ptr[i] + j) = c;
  • 尽量限制变量的范围
  • 使用 fgetsstdin
  • 读取
  • 您的代码中可能存在缓冲区溢出; fgets
  • 的另一个论点