Difference between using strcpy() and copying the address of a the char* in C

后端 未结 4 1517
野性不改
野性不改 2020-12-12 02:05

I have two dynamically allocated arrays. c

char **a = (char**)malloc(sizeof(char*) * 5));
char **b = (char**)malloc(sizeof(char*) * 5));

for (int i = 0; i         


        
4条回答
  •  时光取名叫无心
    2020-12-12 02:40

    They are different. In strcpy() case you are copying the characters, in the assignment case you adjust the pointer to point to the same array.

     a[0] -> allocated memory containing "hello"
     b[0] -> allocated memory not yet initialised
    

    After b[0] = a[0]

    both now point to same memory

     a[0] -> allocated memeory containing "hello"
     b[0] ---^ 
    

    and worse nothing now points to b[0]'s

     allocated memory not yet initialised
    

    so you can never free it; memory leak.

提交回复
热议问题