'How to use the strncpy function in the 3rd array of 2d array strings

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
    char d2arr[6][7] = {
        { 'a', 'a', 'a', 'a', 'a', 'a' },
        { 'b', 'b', 'b', 'b', 'b', 'b' },
        { 'c', 'c', 'c', 'c', 'c', 'c' },
        { 'd', 'd', 'd', 'd', 'd', 'd' },
        { 'e', 'e', 'e', 'e', 'e', 'e' },
    };
    char d3arr[6][7][7];
    memset(d3arr, NULL, sizeof(d3arr));

    strncpy(d2arr[0], d3arr[0][0], sizeof(7));
    strncpy(d2arr[1], d3arr[0][1], sizeof(7));
    strncpy(d2arr[2], d3arr[0][2], sizeof(7));
    strncpy(d2arr[3], d3arr[0][3], sizeof(7));
    strncpy(d2arr[4], d3arr[0][4], sizeof(7));

    printf("%s\n", d3arr[0][0]);
    printf("%s\n", d3arr[0][1]);
    printf("%s\n", d3arr[0][2]);
    printf("%s\n", d3arr[0][3]);
    printf("%s\n", d3arr[0][4]);

    return 0;
}

There is no error message, and the results do not come out, so I ask questions. Please let me know why the string in the 2D array is not copied.



Solution 1:[1]

The problem is here:

strncpy(d2arr[0] , d3arr[0][0] , sizeof(7) );
strncpy(d2arr[1] , d3arr[0][1] , sizeof(7) );
strncpy(d2arr[2] , d3arr[0][2] , sizeof(7) );
strncpy(d2arr[3] , d3arr[0][3] , sizeof(7) );
strncpy(d2arr[4] , d3arr[0][4] , sizeof(7) );

The strncpy function works as under:

strncpy(destination, source, no_of_characters);

But in your code you have swapped destination and source arrays, and as a result, your code doesn't work. Also instead of using 'sizeof(7)' you should use only '7'. Also you should use strncpy_s instead of strncpy as strncpy can be unsafe.

So after all the corrections, here's the code:

strncpy_s(d3arr[0][0], d2arr[0], 7);
strncpy_s(d3arr[0][1], d2arr[1], 7);
strncpy_s(d3arr[0][2], d2arr[2], 7);
strncpy_s(d3arr[0][3], d2arr[3], 7);
strncpy_s(d3arr[0][4], d2arr[4], 7);

Just replace the part with strncpy functions with the above code, and you'll be good to go. Other part of the code is totally fine.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1