Paradox Paradox - 3 years ago 344
C Question

C strcpy array of string pointers

I have an array declared like so:

char *array[4];

which is populated by a different function with strings, i.e. ["one", "two", "three", "four"].

My goal is to copy this array into a new array, excluding the last two elements, so new_array would contain ["one", "two"].

This is what I have tried so far:

int *new_array[2];

for (int i = 0; i < 2; i++){
strncpy(new_array[i], array[i], strlen(array[i]));

But have received the following warning:

warning: passing argument 1 of ‘strncpy’ from incompatible pointer type [-Wincompatible-pointer-types]

note: expected ‘char * restrict’ but argument is of type ‘int *’

extern char *strncpy (char *__restrict __dest,

Answer Source

Your code is very wrong.

First it declares an array of integer pointers (hence the warnings) then those pointers aren't initialized. strncpy isn't the proper function to call (and even if the memory was initialized, it wouldn't null-terminate your strings), you need strdup which does the proper allocation & copy:

char *new_array[2];

for (int i = 0; i < 2; i++){
    new_array[i] = strdup(array[i]);

(on some old systems, strdup may not be available. If you're in that case, just use new_array[i] = malloc(strlen(array[i]+1)); then strcpy(new_array[i],array[i]);)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download