[Solved] copy a const char* into array of char (facing a bug)


When passing an array as argument, array decays into the pointer of FIRST element of array. One must define a rule, to let the method know the number of elements.

You declare char mbuf[16], you pass it to setName(), setName() will not get char[], but will get char* instead.

So, the declaration should be

static void setName(const char* str, char* buf)

Next, char mbuf[16] can only store 15 chars, because the last char has to be ‘null terminator’, which is ‘\0’. Otherwise, the following situation will occur:

// if I use buf in my code it is leading to spurious characters since length is greater than 16 .

Perhaps this will help you understand:

char str[] = "foobar"; // = {'f','o','o','b','a','r','\0'};

So the code should be

static void setName(const char* str, char* buf)
{
    int sz = MIN(strlen(str), 15); // not 16
    for (int i = 0; i < sz; i++) buf[i] = str[i];
    buf[sz] = '\0'; // assert that you're assigning 'null terminator'
}   

Also, I would recommend you not to reinvent the wheel, why don’t use strncpy instead?

char mbuf[16];
strncpy(mbuf, "12345678901234567890", 15);

9

solved copy a const char* into array of char (facing a bug)