Reputation: 3
I need help with breaking a string into an array. I got it to work without storing the info and just printing the tokens. But for this prog, I need to store the tokens strtok made and use a binary search to do a strncmp with 2 elements each being from a different array.
./file "Example input: 'Cause I'm Batman"
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
char delims[] = " ";
char *result = NULL;
int i = 1;
int j = 0;
char sent[1000];
result = strtok(argv[1], delims);
sent[0] = *result;
while(result != NULL)
{
result = strtok(NULL, delims);
sent[i] = *result;
i++;
}
while(j < i)
{
printf(" %p\n", &sent[j]);
j++; //Forgot to add it in first time around
}
return 0;
}
Problem is I'm getting a segmentation fault and I can't seem to get it to store the tokens into an array and I don't understand why. Is it a pointer issue? Passing incompatible data types? Something else?
Edit: Wanted output: "Example" "input:" "'Cause" "I'm" "Batman"
Any help would be great.
Upvotes: 0
Views: 1315
Reputation: 40145
fix like this
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]){
char delims[] = " ";
char *result = NULL;
int i = 0, j;
char sent[1000];
char *parray[32];//32 word
strcpy(sent, argv[1]);//strtok destory string, argv[n] is read only.
result = strtok(sent, delims);
parray[i++] = result;
while(NULL!= (result=strtok(NULL, delims))){
parray[i++] = result;
}
for(j=0; j < i;++j)
printf("%s\n", parray[j]);
return 0;
}
Upvotes: 0
Reputation: 64
When strtok reaches '\0' NUL character in the string, it will return NULL pointer.
In your code 'result' is de-referenceed after making strtok(NULL, delims) call. As a result you will be de-referencing result without making a sanity check for its validity and will end up accessing NULL pointer.
Upvotes: 0
Reputation: 409176
In your case it's very easy to figure out what's causing the crash: You dereference the NULL
pointer.
Think for a minute what will happen with the expression *result
when result
is NULL
.
Also, this error would have taken you less than a minute to find if you used a debugger. When a program crashes, a programmers first instinct should always be to run the program in a debugger.
Upvotes: 1