[Solved] “strncpy_s” Not Working


Your code has several issues.

First of all, your call to strncpy_s does not follow the declaration of strncpy_s, which lists four parameters (if the first parameter is a char * as in your case):

errno_t strncpy_s(
   char *strDest,
   size_t numberOfElements,
   const char *strSource,
   size_t count
);

But much more importantly, you state that you would like to end up with multiple strings in an array first_array[], each holding a shorter version of the input string than the last. But the first_array[] you declared only holds one char * string, the one you initialized first_array[0] to, which is exactly one character long (the terminating null byte):

char* first_array[] = {""};

Even if you declared it to hold five char * (the initialization is not necessary as you copy the contents over anyway)…

char * first_array[5];

…you still haven’t allocated memory space for each of the five char * strings. You just have five pointers pointing nowhere, and would have to allocate memory dynamically, depending on user input.

Because I haven’t even talked about what happens if the user enters more than five characters, let alone 32…

At this point, even if I would post “working” code, it would teach you little. You are apparently following some kind of tutorial, or actually attempting to learn by trial & error. I think the right answer here would be:

Get a different tutorial. Even better, get a good book on C or a good book on C++ as online tutorials are notoriously lacking.

5

solved “strncpy_s” Not Working