I'm using the following code to store stdin into an array. I end up with a host of warnings and a segmentation fault.
while(fgets(str, 256, stdin)){
size_t count = 0;
char** arr = NULL;
char* token = NULL;
char* delim = ' ';
for(int i=0; i < strlen(str); i++)
if (isspace(str[i])) count++;
count++;
arr = malloc(sizeof(char*) * (count));
for(int i=0; i <= count; i++){
token = strtok(str, delim);
arr[i] = token;
}
for (int i = 0; i < count; ++i)
{
printf("%s\n", arr[i]);
}
//if(strncasecmp(str, "quit", 4) == 0) break;
free(arr);
}
I'm a little confused about this warning in compilation
c:34:12: warning: incompatible integer to pointer conversion initializing 'char *' with an expression of type 'int'
[-Wint-conversion]
char* delim = ' ';
^ ~~~
And ofcourse finally when I run it I end up with a seg fault.
admin 123 tyu
Segmentation fault: 11
What am I doing wrong here.
intbecause thecharis getting promoted.for(int i=0; i < strlen(str); i++), it's way too expensive, do it like thisfor(int i=0; str[i] != '\0'; i++), every time you callstrlen()an equivalent to my suggestion loop is executed.