博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
数组与指针
阅读量:7081 次
发布时间:2019-06-28

本文共 2358 字,大约阅读时间需要 7 分钟。

背景:

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

demo代码:

1 #include 
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 the22 // %ld in this code to a %u since it will use unsigned ints23 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$ ./ex8the size of the variable int pointer is 8.the size of the variable char pointer is 8.The size of an int: 4The size of areas (int[]): 20The number of ints in areas: 5The first area is 10, the 2nd 12.The size of a char: 1The size of name (char[]): 7The number of chars: 7The size of full_name (char[]): 14The number of chars: 14name="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/archive/2013/05/05/3060750.html

你可能感兴趣的文章
Yelp的实时流技术之二:将MySQL表数据变更实时流到Kafka中
查看>>
数据不可变之linked-in/rocketdata
查看>>
Java 10新特性前瞻
查看>>
从蚂蚁金服实践入手,带你深入了解 Service Mesh
查看>>
通过DevOps考古学了解生产环境
查看>>
nginx lua指令执行顺序
查看>>
新书问答:Agile Management
查看>>
精益企业中架构师的角色
查看>>
Chrome开发者工具中关于“Deferred long-running timer task(s) ”的警告
查看>>
Windows 下使用 MinGW 编译安装 (G)vim 添加 Lua 等编程语言支持
查看>>
Objective-C基本数据类型
查看>>
利用localStorage本地储存js文件
查看>>
[聊一聊系列]聊一聊百度移动端首页前端速度那些事儿
查看>>
shell script编程小结——附带实例
查看>>
在 Laravel 项目中使用 Glup 之 Laravel-Elixir
查看>>
Nginx、CGI、FastCGI、PHP-CGI、PHP-FPM处理流程
查看>>
Tornado 4.3文档翻译: web框架-RequestHandler和Application 类
查看>>
版本控制总结
查看>>
数字证书、公私钥小记
查看>>
客户端开发流程
查看>>