Semantics of char a[]

后端 未结 6 611
忘掉有多难
忘掉有多难 2021-02-01 23:34

I recently embarrassed myself while explaining to a colleague why

char a[100];
scanf(\"%s\", &a); // notice a & in front of \'a\'

is ve

6条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-02 00:24

    It's been a while since I programmed in C but here's my 2c:

    char a[100] doesn't allocate a separate variable for the address of the array, so the memory allocation looks like this:

     ---+-----+---
     ...|0..99|...
     ---+-----+---
        ^
        a == &a
    

    For comparison, if the array was malloc'd then there is a separate variable for the pointer, and a != &a.

    char *a;
    a = malloc(100);
    

    In this case the memory looks like this:

     ---+---+---+-----+---
     ...| a |...|0..99|...
     ---+---+---+-----+---
        ^       ^
        &a  !=  a
    

    K&R 2nd Ed. p.99 describes it fairly well:

    The correspondence between indexing and pointer arithmetic is very close. By definition, the value of a variable or expression of type array is the address of element zero of the array. Thus after the assignment pa=&a[0]; pa and a have identical values. Since the name of the array is a synonym for the location of the initial element, the assignment pa=&a[0] can also be written as pa=a;

提交回复
热议问题