Home > OS >  C char array lose pointer after assingment loop
C char array lose pointer after assingment loop

Time:10-28

I'm learning C and I'm so stucked in when allocating memory for a char array in a struct array.

After assigning the value to the char arrays in the first loop, when I try to access the value in a second loop.

Could please anyone help me? thank you

CodePudding user response:

For starters this code snippet invokes undefined behavior

char string[numDigits];
sprintf(string, "%d", 12345);

because the array string does not have a space to store the terminating zero character '\0' of the string built by the call of sprintf. You need to declare the array like

char string[numDigits  1];

Secondly this code snippet

table[i].str = malloc(sizeof(char) * numDigits);  
table[i].str = string; 

produces a memory leak because at first a memory was allocated and its address was assigned to the pointer table[i].str and then the pointer was reassigned.

You need to write

#include <string.h>

//...

table[i].str = malloc(sizeof(char) * ( numDigits   1 ));  
strcpy( table[i].str, string ); 

And at last for loops in the program shall be rewritten like

for (i = 0; i < n; i  )
            ^^^^^^
  • Related