I want to break a sentence into words using pointers.
I wrote some code but I am really confused because I get segmentation fault.
kindly help me out.
Thanks in advance.
char **breakstring(char *str)
{
char **temp=(char **)malloc(5*sizeof(char *));
char **temp_store = temp;
while((*str) != '/0')
{
while((*str != '\0') && *str!=' ')
{
**temp=*str;
**temp++;
*str++;
}
str++;
temp++;
}
return temp_store;
}
int main()
{
char **arra;
char *arr="this is a stupid string";
arra=breakstring(arr);
return 0;
}
You allocated 2 pointers. Your input string has more than 2 spaces. If you still want to use dynamic memory, you’ll have to periodically call
reallocto ask for more space, or possibly introduce some other arbitrary maximum that’s greater than 2.What this says is “while the current char of the string is not a space, add the string to
temp, and advance. So if you’re called with"This is a ..."you’ll end up with"This is a ...","his is a ...","is is a ...", etc. Inside this loop you want to advancestrwithout assigning totemp. (You’ll also want to add the condition*str, i.e.while (*str && *str != ' ')) Outside the loop you’ll want something like*temp++ = str;, then skip all the space characters. (You might also want to add aNULterminator to stop the string, but you’ve called the function with aconst char *string literal, so to maintain that you’d probably have to copy the whole string onto the heap.)All in all, the amount of heap allocations we’re leading into here is somewhat un-C-like for string manipulation. I suggest instead of returning a heap allocation and passing constant strings, you look into an interface like
strsep()(the better version of the uglystrtok()), which modifies the caller’s buffer.Update: @Rohan is also right about the return value issue. If you keep doing
temp++you need to remember the original position of the start of the allocation, and return that. Although, I would re-iterate looking intostrseporstrtok_r.