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

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

    In this particular case they are not equivalent. If to assign a[0] to b[0] then there will be a memory leak or the same memory can be deleted twice when the arrays will be deleted.

    So the correct approach is to use function strcpy.

    Take into account that there is a typo in your example. Instead of

    for (int i = 0; i < 7, i++) {
      a[i] = (char*)malloc(sizeof(char)*7);
      b[i] = (char*)malloc(sizeof(char)*7);
    }
    

    there shall be

    for (int i = 0; i < 5, i++) {
      a[i] = (char*)malloc(sizeof(char)*7);
      b[i] = (char*)malloc(sizeof(char)*7);
    }
    

    However there are situations when it is much simpler to use pointer assignments. Consider task of swapping of two rows of the "same" dynamically allocated array. For example let's assume that we want to swap a[0] and a[4]. We could do the task the following way using strcpy

    char *tmp = malloc( 7 * sizeof( char ) );
    
    strcpy( tmp, a[0] );
    strcpy( a[0], a[4] );
    strcpy( a[4[, tmp );
    
    free( tmp );
    

    However it will be much simpler to swap only pointers:)

    char *tmp = a[0];
    a[0] = a[4];
    a[4] = tmp;
    

    There is no any need to alloocate additionally memory and then to free it.:)

提交回复
热议问题