关于数组作为参数传递以及数组名和对数组名去址的差异

  • 这里再次探讨一下对于数组a,a和&a有什么不同
     1  #include <stdio.h>
     2  
     3  void change_array(char*, int);
     4  
     5  int main(void)
     6  {
     7      char a[10] = "abcdefg";
     8      printf("&The address of origin a = %p
    ",&a);
     9      printf("a1: %p
    ", a); 
    10      printf("sizeof(&a): %d
    ", sizeof(&a));
    11      printf("sizeof(a) %d
    ", sizeof(a));
    12      change_array(a, 10);
    13      printf("&The address of later a = %p
    ",&a);
    14      printf("a2: %p
    ", a); 
    15      printf("%s
    ",a);
    16      return 0;
    17  }
    18  
    19  void change_array(char *a, int n)
    20  {
    21      scanf("%s", a);//To my surprise, this gets the same result as using either a or &a.
    22      printf("arraysizeof(&a): %d
    ", sizeof(&a));
    23      printf("arraysizeof(a): %d
    ", sizeof(a));
    24      printf("&array: %p
    ", &a);
    25      printf("array1: %p
    ", a); 
    26  }
    27  
    28  /***************************************************
    29   * &The address of origin a = 0x7ffee2cdd0a0
    30   * a1: 0x7ffee2cdd0a0
    31   * sizeof(&a): 8     ---------->在这,&a对应的字节是8,在我的电脑中,对指针p取址(&p)得到的大小也是8
    32   * sizeof(a) 10      ---------->a对应的字节是10,说明a的大小就是a[10]中的是,即数组大小。
    33   * xxxx
    34   * arraysizeof(&a): 8 ---------->这里是8,没疑问,说明指针大小是8
    35   * arraysizeof(a): 8  ---------------------->>>>>>>>>>这里有疑问.放下面说!!!
    36   * &array: 0x7ffee2cdd088
    37   * array1: 0x7ffee2cdd0a0
    38   * &The address of later a = 0x7ffee2cdd0a0
    39   * a2: 0x7ffee2cdd0a0
    40   * xxxx
    41   * *************************************************/

    接着代码中35行:通过上面输出结果,我们知道在mian中的数组a和在array_change中的数组a的地址是一样的!即0x7ffee2cdd0a0,注意a和&a的不同.那为什么在main中的sizeof(a)是10个字节的大小,而在array_change中的sizeof(a)只有8个字节的大小呢?经查证,在将数组名作为参数传递时,只是传递了数组地址,并没有将数组的大小一同传过来,所以我们要定义另外一个参数来传递数组大小.

  • 为了证明指针本身的大小是8,我写多了一个程序(指针本身大小在不同系统可能不同)
     1 #include <stdio.h>
     2  
     3  int main(void)
     4  {
     5      char *pa = NULL;
     6      char a = 'q';
     7      pa = &a; 
     8      printf("sizeof(a): %d
    ", sizeof(a));
     9      printf("sizeof(&a): %d
    ", sizeof(&a));
    10      return 0;
    11  
    12  }
    13  
    14  /*****************************
    15   * sizeof(a): 1
    16   * sizeof(&a): 8
    17   * ***************************/
原文地址:https://www.cnblogs.com/busui/p/5727611.html