|
|
Jim <jim.moneytime@xxxxxxxxx> writes:
> On Mar 28, 1:09 pm, fred.l.kleinschm...@xxxxxxxxxx wrote:
>> On Mar 28, 10:02 am, Jim <jim.moneyt...@xxxxxxxxx> wrote:
>> > I have to create a function that will take a sentence and breakout the
>> > words and save them into an array. For some reason, I can't get it
>> > working. I keep getting a segmentation fault being caused by
>> > strcpy(). Can someone please tell me what I'm doing wrong:
>>
>> > 88 void displayPigLatin(char *str) {
>> > 89 void encode(char *sPtr);
>> > 90
>> > 91 char
>> > 92 *arrStr[MAXWORDS][WORDSIZE],
>> > 93 *tokenPtr,
>> > 94 *tmpStr;
>> > 95
>> > 96 int cnt;
>> > 97
>> > 98 strcpy(arrStr[0][0], str);
>> > 99 tokenPtr = strtok(arrStr[0][0], " ");
>> > 100 printf("%s\n", tokenPtr);
>>
>> arrStr[0][0] has not yet been set to point to any storage location.
>> When you copy str to it, you are copyihng to some random place,
>> corrupting memory.
>> --
>> Fred Kleinschmidt
best not to quote sigs...
> so how can I fix that?
By not doing it! Ok, glib, but how can anyone guess how you intended
this to work? You might have intended to copy each word into the
WORDSIZE char spaces in the arrStr variable. In that case the
declaration is wrong (you don't need the *).
You might have intended the arrStr to be an array of pointers, but
only a 1D array (then the * is right and the [WORDSIZE] is wrong).
The plan might have been to point to each word returned by strtok.
In both cases the initial call to strcpy seems wrong. It is a good
idea to copy the string before letting strtok loose on it, but the
copy as you have it seems out of place.
I would copy the string counting words as I go. Then I'd allocate
(with malloc) an array of pointers big enough for the job (we now
know having counted) and then I'd scan again, setting each of the
pointers to the right place in the copied string and setting the first
' ' to '\0' as I go. I would not bother with strtok at all.
--
Ben.
|
|