【问题标题】:multiple string input in an array of char pointer字符指针数组中的多个字符串输入
【发布时间】: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",&amp;p); --> scanf("%d%*c",&amp;p); 1) 删除 i++; 2) 还 free 应用 ptr[i]

标签: c arrays pointers malloc


【解决方案1】:

您的问题是您首先在 for 循环开始时增加 i,然后在循环结束时增加第二次,因此 两次 而不是一次。您需要删除最后的i++;


注意事项:

  • don't cast the result of malloc
  • 你需要free你分配的char*s(即“ptr[i]”)
  • 使用ptr[i][j] = c; 而不是*(ptr[i] + j) = c;
  • 尽可能限制变量的范围
  • 使用fgets 读取stdin
  • 您的代码中可能存在缓冲区溢出; fgets 的另一个论点

【讨论】:

  • 我的循环输入 p-1 次。为什么?
  • @Atul for 循环应该与i &lt; p 一样长,因此循环运行for 循环。无论如何,究竟是哪个循环?由于一个非常令人困惑的错字,我删除了旧评论。 ^^
  • 外部 for 循环从 0 运行到 p-1,因此它应该输入 p 次,但即使按照建议进行更正后,它也需要输入 p-1 次。你能帮帮我吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-28
  • 1970-01-01
  • 1970-01-01
  • 2012-09-29
  • 1970-01-01
相关资源
最近更新 更多