Search code examples
cprintfstrncpy

C: using sprintf and strncpy inserting data into an array of pointers


I have a structure that has an array of pointers. I would like to insert into the array digits in string format, i.e. "1", "2", etc..

However, is there any difference in using either sprintf or strncpy?

Any big mistakes with my code? I know I have to call free, I will do that in another part of my code.

Many thanks for any advice!

struct port_t
{
    char *collect_digits[100];

}ports[20];

/** store all the string digits in the array for the port number specified */
static void g_store_digit(char *digit, unsigned int port)
{
    static int marker = 0;
    /* allocate memory */
    ports[port].collect_digits[marker] = (char*) malloc(sizeof(digit)); /* sizeof includes 0 terminator */
    // sprintf(ports[port].collect_digits[marker++], "%s", digit);
    strncpy(ports[port].collect_digits[marker++], digit, sizeof(ports[port].collect_digits[marker]));
}

Solution

  • Yes, your code has a few issues.

    • In C, don't cast the return value of malloc(). It's not needed, and can hide errors.
    • You're allocating space based on the size of a pointer, not the size of what you want to store.
    • The same for the copying.
    • It is unclear what the static marker does, and if the logic around it really is correct. Is port the slot that is going to be changed, or is it controlled by a static variable?

    Do you want to store only single digits per slot in the array, or multiple-digit numbers?

    Here's how that function could look, given the declaration:

    /* Initialize the given port position to hold the given number, as a decimal string. */
    static void g_store_digit(struct port_t *ports, unsigned int port, unsigned int number)
    {
      char tmp[32];
    
      snprintf(tmp, sizeof tmp, "%u", number);
      ports[port].collect_digits = strdup(tmp);
    }