C: Does the address operator (&) produce a pointer (address + type) or just an address?

后端 未结 4 1323
感动是毒
感动是毒 2021-01-14 23:30

Most of what I\'ve read about the address operator, &, says it\'s used to get just that - an address. I recently heard it described differently, though, as

4条回答
  •  不思量自难忘°
    2021-01-14 23:43

    The & operator simply returns a pointer to its operand. If its operand was an int the resulting type will be int*. If its operand was an int* the resulting type will be int**. For example, this program:

    #include 
    
    struct test {
      int a;
      int b;
      int d;
    };
    
    int main ( ) { 
        struct test foo = { 0, 0, 0 } ; 
        printf( "%lu\n", (unsigned long)(&foo + 2) - (unsigned long)&foo );
    }
    

    Outputs 24 on my machine because the sizeof(struct test) is 12, and the type of &foo is known to be struct test *, so &foo + 2 calculates an offset of two struct tests.

提交回复
热议问题