Similarities and differences between arrays and pointers through a practical example

前端 未结 5 1803
时光取名叫无心
时光取名叫无心 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:45

    That's normal ...

    First, scanf requires a pointer. "a" and "b" already are pointers ! So :

    /* 1 */
    scanf("%d", a);
    printf("%d\n", a[0]);
    
    /* 2 */ 
    scanf("%d", b);
    printf("%d\n", b[0]);
    

    Will work.

    Normally /* 1 */ shouldn't work. But gcc transforms "&a" by "a" because "&a" doesn't have any sense.

    printf("&a = %p\n", &a);
    printf("a = %p\n", a);
    printf("&b = %p\n", &b);
    printf("b = %p\n", b);
    
    &a = 0x7ffff6be67d0
    a = 0x7ffff6be67d0
    &b = 0x7ffff6be67c8
    b = 0xb0b010
    

    You can't take the adress of a. But b is a "normal variable" of type pointer, and thus you can take it's address by "&b".

    On /* 2 */ you're putting the value entered by the user in b and thus, *b (or b[0]) will crash unless the user will enter a valid readable memory address.

提交回复
热议问题