Lisa
Lisa

Reputation: 3181

Patial copy of string array

Can I do something like this, to copy string array content from one to another?

char **words = (char **)malloc(sizeof(char*) * lines_allocated); 
char **childWords = (char **)malloc(sizeof(char*) * len1); 
int i;
for(i = startIndex; i < endIndex; i++) {
    childWords[i] = words[i];       
}

Upvotes: 0

Views: 94

Answers (3)

ajay
ajay

Reputation: 9680

You are copying pointers to the strings, not the strings themselves. You should change your for loop to

for(i = startIndex; i < endIndex; i++) {
    childWords[i] = strdup(words[i]);  // creates a new copy of the string       
} 

strdup duplicates the string by allocating enough memory to copy the string passed to it, i.e., it returns a pointer to a new string which is a duplicate of the string pointed to by words[i]. The pointer can be passed to free. It's declared in the string.h header file.

Please note that you should not cast the result of malloc. There's no benefit and it can lead to bugs if you forget to include the stdlib.h header file. Also strdup is a part of the POSIX standard and under the hood, it effectively does the same thing as malloc and then strcpy. Read more here What does strdup do?

Upvotes: 3

Chris
Chris

Reputation: 2763

What you are doing is duplicating the pointers to the lines of text, so that you will end up with two arrays of char*'s which point to the same physical memory containing the actual words.

The problem with this is that if you change the memory through 'words' then 'childWords' would change because they point to the same memory.

The safest way to do this would be to get the string length of each 'word' and allocate new memory, copying the string over so that 'childWords' points to different memory.

Upvotes: 2

James McPherson
James McPherson

Reputation: 2576

Why not use memcpy() or bcopy() instead? Also, I don't believe you need to cast the result from malloc().

Upvotes: 1

Related Questions