I'm using with a smaller piece of code to test functionality for a larger (beginner) program, but I don't understand the difference between two strings.
I found and used:
#include <stdio.h>
#include <string.h>
int main()
{
char *string, *found;
string = strdup ("1/2/3");
printf("Orig: '%s'\n",string);
while ((found = strsep(&string,"/")) != NULL )
printf ("%s\n",found);
return (0);
}
and this print the tokens one at a time.
Then when I try and move to a user entered string:
#include <stdio.h>
#include <string.h>
int main()
{
char string[13],
char *found, *cp = string;
fprintf(stderr, "\nEnter string: ");
scanf("%12s",string);
printf("Original string: '%s'\n",string);
while((found = strsep(&cp,"/,-")) != NULL )
printf("%s\n",found);
return(0);
}
I get a seg fault. I understand the basics of pointers, arrays and strings, but clearly I'm missing something, and would love for someone to tell me what it is!
Also - if I change printf("%s\n",found);
to printf("%i\n",found);
I get some junk integers returned, but always the correct amount, e.g. If I enter 1/2/3
I get three lines of integers, 1111/2222
I get two lines.
Thanks!
-Edit-
There was an adittional problem with strsep
, detailed here. Thanks all.
In the first piece of code, string
is assigned the return value of strdup
, which allocates space for the string to duplicate and returns a pointer to that allocated space.
In the second piece of code, string
uninitialized when it is passed to scanf
, so scanf
is reading the invalid value in that pointer and attempting to dereference it. This invokes undefined behavior which in this case manifests as a crash.
You need to set aside space for the user's string. A simple way to do this is to create an array of a given size:
char string[80];
Then tell scanf
how many characters it can read in:
scanf("%79s",string);