Jim said:
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);
....
Fred and Ben have discussed details of your code. I recommend addressing
the problem as one of specification.
You said that you have to "create a function that will take a sentence and
breakout the words and save them into an array." Let's start there. Let's
specify three things:
1. Exactly what the input to the function is.
2. What the function will do.
3. What the result will be.
Input:
You have already said that it will "take a sentence". One reasonable
implementation is that the sentence is contained in a C string. Is that
OK? Since it is a sentence, I assume that it may be terminated with
punctuation. Since you are looking for word, they will probably get
discarded, but you should say so.
Processing:
You said that it will "break out [two separate words in this use] the words
and save them in an array." You need to define how words are delimited.
Usually this will be a space, but could be punctuation. How do you want to
treat hyphens separating letters? It would probably be easiest to assume
they separate words. How about apostrophe? The best assumption is that
they are contained within a word -- in other words treat them similar to
letters.
You want to save the words in an array. How will they be stored in an
array? Will you have an array for a fixed number of words? If so, what
happens if more words are found? What will you do with duplicate words --
enter them for each instance or only once? Will you retain the original
capitalization? Will the words be stored in a two dimensional array or be
stored in a separately allocated array with a pointer in the array of words?
Output:
Finally, what will the function do when it has placed the words in an
array? Will it pass it back to the caller? If so, will the address of the
array be passed from the caller to the function, or will the function
allocate the array dynamically and return the address of the array to the
caller? Will it instead be placed in an array accessible to both caller
and the function (usually not a good idea)? How will the end of the word
list be indicated?
These are the details that I would write in the header to such a function.
A user should be able to read that header and know what the results will
be without looking at the code.
Once that is done, writing the code becomes much easier. You may specify
one thing and then change your mind during development. That's OK -- just
remember to change the description to match.