What is the difference between “char *var[3]” and “char var[3][15]”?

前端 未结 4 760
栀梦
栀梦 2021-01-23 14:13

I am confused between the following two ways:

char var[3][15] = {\"Hello_world!\", \"good\", \"bad\"}; // as known this is for an 2D array.  
char *var[3] = {\"H         


        
4条回答
  •  遇见更好的自我
    2021-01-23 14:42

    The first is actually creating a block of 45 (3*15) bytes in memory, with a base at some memory location that will be called var. C will let you address these as a two-dimensional array so that var[a][b] is the same as *(var + a*15 + b). The compiler will then pre-fill those 45 bytes with your strings in the right locations to maintain the 2D-array feel.

    The second method is allocating one block of memory with 3 pointers. If your pointers are 8 bytes each, then var is a 1D array of 24 (3*8) bytes. In addition, C will create some other arrays somewhere else in memory with your data strings. It will then point the former to the latter. That is, the following is roughly equivalent to your second method:

    char s1[] = "Hello_world!";
    char s2[] = "good";
    char s3[] = "bad";
    char *var[3] = { &(s1[0]), &(s2[0]), &(s3[0]) };
    

    Note however that the equivalence from the first method of var[a][b] == *(var + a*15 + b) is not maintained. For example, var[0] will point to s1, which could technically be anywhere in memory (and has no relationship to where s2 or s3 are). Then var[0][b] is some offset from that location.

提交回复
热议问题