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

后端 未结 4 1545
野性不改
野性不改 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:35

    Understand that a[0] and b[0] in this case are themselves arrays (or pointers to characters arrays, to be more precise)

    strcpy() would traverse through each individual element of the character array which a[0] points to. While the assignment b[0] = a[0] will just make b[0] point where a[0] is pointing, resulting in memory leak (the memory to which b[0] was pointing cannot be free'd).

    Visualize the state of affairs using a simple figure like this -

         +---+ -->  +------+          +---+---+---+---+---+----+
         | a |      | a[0] | ------>  |'H'|'E'|'L'|'L'|'O'|'\0'| 
         +---+      +------+          +---+---+---+---+---+----+
                    | a[1] |
                    +------+
                    | ...  |
                    +------+    
                    | a[n] |
                    +------+                                    
    

提交回复
热议问题