简体   繁体   中英

multiple string input in an array of char pointer

I am trying to take multiple string input in an array of char pointer,the no. of strings is also taken from user. I have written following code but it does not work properly, Please if somebody could help me to fix it? It is taking some random no. of inputs not given by user.

#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;    
}

Your problem is you increment i first at the beginning of the for-loop, second at the end of the loop, thus two times instead of one. You need to remove the i++; at the end.


Notes:

  • don't cast the result of malloc
  • you need to free the char* s you allocated (ie " ptr[i] ")
  • use ptr[i][j] = c; instead of *(ptr[i] + j) = c;
  • confine the scope of variables as much as possible
  • use fgets to read from stdin
  • buffer overflows are possible in your code; another argument for fgets

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM