数组与指针

背景:

  这片文章主要是记录以前的误区,以前C/C++这块还是大学中学习的一点知识,好久不用,基本都忘记啦。一直误以为数组的大小和指针的大小一样,最近通过学习learn c the hard way发现并不是这样。这个其实没有太多可说的,直接上demo。

demo代码:

 1 #include <stdio.h>
 2 
 3 int main(int argc, char *argv[])
 4 {
 5     int areas[] = {10, 12, 13, 14, 20};
 6     char name[] = "Zhaosc";
 7     char full_name[] = {
 8         'Z', 'h', 'a', 'o',
 9         ' ', 'S', 'h', 'u', ' ',
10         'c', 'h', 'a', 'o', '\0'
11     };
12     
13     int a = 10;
14     int *a_ptr = &a;
15     char c = 'b';
16     char *c_ptr = &c;
17 
18     printf("the size of the variable int pointer is %ld.\n", sizeof(a_ptr));
19     printf("the size of the variable char pointer is %ld.\n", sizeof(c_ptr));
20 
21     // WARNING: On some systems you may have to change the
22     // %ld in this code to a %u since it will use unsigned ints
23     printf("The size of an int: %ld\n", sizeof(int));
24     printf("The size of areas (int[]): %ld\n",
25            sizeof(areas));
26     printf("The number of ints in areas: %ld\n",
27            sizeof(areas) / sizeof(int));
28     printf("The first area is %d, the 2nd %d.\n",
29            areas[0], areas[1]);
30     
31     printf("The size of a char: %ld\n", sizeof(char));
32     printf("The size of name (char[]): %ld\n",
33            sizeof(name));
34     printf("The number of chars: %ld\n",
35            sizeof(name) / sizeof(char));
36     
37     printf("The size of full_name (char[]): %ld\n",
38            sizeof(full_name));
39     printf("The number of chars: %ld\n",
40            sizeof(full_name) / sizeof(char));
41     
42     printf("name=\"%s\" and full_name=\"%s\"\n",
43            name, full_name);
44     
45     return 0;
46 }

运行结果:

zhaoscmatoMacBook-Pro:c zhaosc$ ./ex8
the size of the variable int pointer is 8.
the size of the variable char pointer is 8.
The size of an int: 4
The size of areas (int[]): 20
The number of ints in areas: 5
The first area is 10, the 2nd 12.
The size of a char: 1
The size of name (char[]): 7
The number of chars: 7
The size of full_name (char[]): 14
The number of chars: 14
name="Zhaosc" and full_name="Zhao Shu chao"

分析:

根据输出一行一行分析

1.int和char的指针在内存的大小都是8个字节,指针在内存中的大小和指针类型没有区别,例如函数指针也是一样的。

2.int在内存占用4个字节,这个是不确定的,和具体的操作系统位数有关系。

3.int数组在内存中占用20个字节,正好是4*5.areas中有5个整数。

4.char在内存中占用1个字节,这个是确定的。

5.char数组占用内存是7个字节,同样为1*7.

Note:如博文中存在问题,请大家及时指出,我会及时纠正,谢谢。

原文地址:https://www.cnblogs.com/zhaosc/p/3060750.html