Similarities and differences between arrays and pointers through a practical example

前端 未结 5 1800
时光取名叫无心
时光取名叫无心 2020-12-05 15:56

Given the following code:

#include 
#include 

int main()
{
    int a[1];
    int * b = malloc(sizeof(int));

    /* 1 */
             


        
5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-05 16:41

    The array a is placed on the stack, the address for the first element is the same as the address of a. &a[0] and &a is the same address

    The array b is allocated with malloc, the address for the storage is on the heap, whereas the address for the pointer b is on the stack. &b[0] is not the same address as &b.

    That's why the first scanf and printf works but not the second.

    The C-FAQ explains it in much greater detail.

提交回复
热议问题