0

I am working on a C function to split a string of letters into an array, however it keeps seg faulting and I have no idea why.

I have run it through DDD a few times, it was not of much help.

char* stringToArray(const char *desc)
{
    int i = 0;
    int j = 0;
    char *array[5][10] = {{0}};/*5 words, 10 chars each*/

    while (desc[i] != '\0')
    {
        if (desc[i] != ' ') {
            *array[j][i] = desc[i]; /*seg faults here*/
        }

        else {
            j++;
        }
        i++;
    }
    return **array;
}

Any help would be greatly appreciated Thanks.

7
  • 2
    Each array[J][I] is a pointer. You haven't made any of all those pointers point to somewhere valid. Commented Aug 9, 2011 at 8:55
  • ahh ok, so I want to remove that * and off we go Commented Aug 9, 2011 at 8:56
  • 1
    You also shouldn't return a pointer to a stack allocated variable (array). That won't work. Commented Aug 9, 2011 at 8:57
  • Thanks, found that out just before, changed the function to a void and its no longer returning anything. Commented Aug 9, 2011 at 8:58
  • Removing the * works only locally, inside the function. Once the function returns the array ceases to exist and the return value (the pointer to the inexistent array) is unusable. Consider passing to the function the array that receives the words. Commented Aug 9, 2011 at 8:59

1 Answer 1

1

You will need to make your array static or allocate some memory for it - returning a pointer to a local array won't work.

You also might want to check out strtok.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.