c++strncpy

Using strncpy to copy a char* pointing to an array of names


I have an array of names test1,test2... I need to make new array with only filterd names. I am bound to use char*.

const char* names[randomLength] = {"test1","test2","test3"...};

I need to create a new array with partial names in the array

const char* filteredNames[randomLength-values];

strncpy(*filteredNames,*names,sizeof(a)/sizeof(char)-values);

I am expecting filteredNames to be test1,test2. But this is causing segmentation fault. Please help me fix this and alos suggest better approach.

Thanks.

EDIT:

Answer by @Jabberwocky works. Thanks.

for (int i = 0; i < randomLength-values; i++)
  filteredNames[i] = names[i];

Comment by @mch doesn't work in cases like

void test(char**& filterednames)
{
...
...
memcpy(names,filterednames,sizeof(filterednames));
...
}

This results in a segmentation fault. Please point out my mistake.

Thanks.


Solution

  • You probably don't want strncpy here but your want something similar to this:

    const char* names[randomLength] = {"test1","test2","test3"...};
    ...
    int value = 2;
    const char* filteredNames[randomLength-values];
    ...
    for (int i = 0; i < randomLength-values; i++)
      filteredNames[i] = names[i];  // copy only the pointer
    

    Be aware that const char* filteredNames[foo]; when foo is not a compile time constant (VLAs, or variable length arrays) is not standard C++, but an extension for some C++ compilers.