int num_arrays;
char *p[20];
char tempc;
int i=0;
do
{ p[i]=malloc(sizeof(int));
scanf("%s",p[i]);
tempc=*p[i];
++i;
}while(tempc=='x');
num_arrays=atoi(p[0]);
When i write num_arrays=atoi(..),gcc give me segmentation fault or memory
stack is exceeded, I don’t understand why it behaves like that
can anyone explain, why?
You haven’t allocated any memory inp, so its elements point to random locations. You can allocate memory for strings with a maximum length of 100 like this:Or else you want an array of characters, not of strings, in which case you should declare it like
In this case, you must not try to read strings into each element with scanf though.
Update after the missing code part has been added:
You are allocating
sizeof(int)bytes of memory for your strings, which is most likely 4, i.e. your input strings read byscanfmust not be longer than 3 characters. Otherwise you have a buffer overrun error, which may lead to the segmentation fault you are struggling with.Moreover,
tempc=p[i]assigns a pointer value to a character variable! This value, converted to a character, will almost surely never be equal to'x'.I guess you are trying to get the first character of
p[i], which would bep[i][0]or*p[i].I also suspect that your loop condition is the opposite of what you had in mind: right now the loop repeats as long as
tempcis equal to'x'– you probably wanted to repeat untiltempcbecomes'x'. And you should also check for your loop not running more than 20 times: