I'm trying to take a string and break it into "word" components and store that in an array of strings. "Hello my name is Bill." should give back a char** with elements, "Hello", "my", "name", "is", and "Bill."
My code will compile however I keep encountering a runtime error (I don't get warnings anymore and my debugger gdb doesn't work)>
I'm running on minGW on Window 8.
#include <stdio.h>
#include <stdlib.h>
char** words(char* string)
{
int i = 0;
int j = 0;
int k =0;
int count = 0;
char** stringArray = (char**) malloc(sizeof(char)*30*30);
while( string[i] != '\0' )
{
if(string[i] != ' ')
{
j =0;
while(string[i+j+1] != ' ')
{
j++;
}
i = i+j;
for(k=0; k<=j; k++)
{
stringArray[count][k] = string[i+k];
}
count++;
}
i++;
}
return stringArray;
}
int main()
{
char message[20] = "abcd efgh ijkl mno";
char** wordArray = words(message);
printf("%c\n\n", wordArray[0][0]);
int i =0;
while(wordArray[i])
{
printf("%s\n", wordArray[i]);
i++;
}
printf("\nThe problem is not with the words function");
return 0;
}
char **
but it doesn't actually contain any pointers tochar *
. You're almost certainly dereferencing an invalid address because of this.string
andstringArray
are also reserved identifiers. – Paul Griffiths Oct 4 at 23:38char
array and incorrectly point achar **
at it. You shouldmalloc()
an array ofchar *
, and then for each of them,malloc()
space for your individual strings. I also can't see that you ever put any terminating\0
in your strings. You should also get a better compiler if all your stuff isn't working. – Paul Griffiths Oct 4 at 23:44