1

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;    
}
Alan Stokes
  • 18,815
  • 3
  • 45
  • 64
Atul
  • 61
  • 2
  • 7

1 Answers1

2

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 (i.e. "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
Community
  • 1
  • 1
cadaniluk
  • 15,027
  • 2
  • 39
  • 67
  • My loop is taking input p-1 times .why? – Atul Sep 08 '15 at 18:55
  • @Atul The for loop should run as long as `i < p`, therefore the loop runs for loop. Anyway, which loop exactly? I removed the old comment because of a pretty confusing typo. ^^ – cadaniluk Sep 09 '15 at 14:55
  • the outer for loop is running from 0 to p-1 therefore it should take input p times, but even after making corrections as suggested , it takes input p-1 times. Can you help me out? – Atul Sep 20 '15 at 19:54