while working on a simple little utility I came across something I don't quite understand
why is it that
Code:
char str[] = "first,second,third";
works for strtok()
but
Code:
char *str = "first,second,third";
ends in a segfault that even though I trace the stack I cant figure out why for the life of me
Now it's been a while since I was in class for C, since I've been programming professionally for years but to the best of my knowledge
char *blah = "this is a const char *";
and char blah[] = "this is a const char*";
were the same exact thing.
The examples were compiled on a Linux x86 system
anyway, here's the sample codes
Code:
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
char str[] = "first,second,third";
char *result = NULL;
char *ptr = str;
printf("%s\n",str);
result=strtok(ptr,",");
while(result)
{
printf("%s\n",result);
result = strtok(NULL,",");
}
return 0;
}
the above WORKS
Code:
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
char *str = "first,second,third";
char *result = NULL;
char *ptr = str;
printf("%s\n",str);
result=strtok(ptr,",");
while(result)
{
printf("%s\n",result);
result = strtok(NULL,",");
}
return 0;
}
the above results in a segmentation fault