Reputation: 33
I'm working on a function which is supposed to take an array of elements defined by a struct.
typedef struct word{
char word[100];
double weight;
} word;
The function takes in a pointer, word *words and creates a subarray which includes only the word elements which are above a certain value n.
I want to use strncpy for this, so I wrote the following:
char dest[numwords]; //the number of words in the array
strncpy(dest, *words, numwords -n);
However, I don't think this code will create the subarray I desire. For example, if the array is {"word1", "word2", "word3", "word4", "word5"} and I want the sub array to be {"word4", "word5"}, using the code above, numwords - n = 4-2, which will give me {"word1", "word2", "word3"} instead.
How do I resolve this? Thanks.
Upvotes: -1
Views: 45
Reputation: 67476
char **copyStr(const word *src, size_t nElements)
{
char **result = NULL;
if(src && nElements)
{
result = malloc(nElements * sizeof(*result));
if(result)
{
for(size_t index = 0; index < nElements; index++)
{
size_t len = strlen(src[index].word);
result[index] = malloc(len + 1);
if(result[index])
{
memcpy(result[index], src[index].word, len + 1);
}
else {/* handle error */}
}
}
}
return result;
}
Upvotes: 0