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])); }
Yes, your code has a few issues.
malloc(). It’s not needed, and can hide errors.markerdoes, and if the logic around it really is correct. Isportthe 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: