I'm pretty new to C, but have programmed a great deal in both Java and Python. So I got the basics going – however, C keeps hitting me with this Segmentation fault: 11 no matter how I wrap my head around my code. I suspect the problem may be that I'm accessing beyond the bounds of my array, namely in this part:
ordListe[i] = (char*)malloc(n);
strcpy(ordListe[i], ord);
For hours I've been at a loss how to solve this, so now I turn to you: what am I missing? I couldn't find many posts involving pointers to pointers out there with a similar problem, so i assume this will be of some help to others in the future too. Full function where the problem occurs:
char** split(char* s)
{
char* setning = (char*) malloc(strlen(s) + 1);
strcpy(setning, s); //Setning blir det samme som s, saa vi slipper aa roere s
printf("%s\n", setning); //TNB: Feilsoeking
char* ord = (char *) malloc(strlen(setning) * sizeof(char)); //Henter ut ordet
ord = strtok(setning, " "); //Henter foerste ord
printf("%s", ord);
int i = 0;
size_t n = 0;
char** ordListe = (char**) malloc(strlen(s) * sizeof(char)); //Lager en liste vi kan lagre verdiene i
ordListe[strlen(setning)+1] = NULL;
while(ord != NULL)
{
n = strlen(ordListe[i]) + 1;
ordListe[i] = (char*)malloc(n);
strcpy(ordListe[i], ord);
i++;
ord = strtok (NULL, " "); //Beveger den videre
}
free(setning);
return ordListe;
}
The purpose of the function is to split a string and store the individual parts in a pointer-to-pointer array and return said array. Thanks in advance!
Here is one way to do it: