Reputation: 61
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;
}
Upvotes: 1
Views: 1975
Reputation: 15229
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:
malloc
free
the char*
s you allocated (i.e. "ptr[i]
")ptr[i][j] = c;
instead of *(ptr[i] + j) = c;
fgets
to read from stdin
fgets
Upvotes: 2