[备忘] 重温十年前的C基础 - sizeof

正常的咱就不看了, 只看不正常, 但不是变态的情况, 所有情况都是基础 IPL32 数据模型

char *s="0123";
sizeof(s) //输出为5, 因为字符串常量最后还隐藏了 '\0'

int aa[][3] = { {1,2,3},{4,5,6},{7,8,9} };
sizeof(aa);//输出为9*4=36, 二维数组本质也连续的内存, 从分配多少内存刚好够用的角度来考虑就很自然了

int bb[5] = {0,1,2,3,4};
func(bb);
void func(int bb[5]){
    sizeof(bb);//输出为4, 本质上是一个指针, 这个形参写法容易迷惑人, 其实等于  int b[]

int cc[] = {0,1,2,3,4,5};
int *p = cc;
sizeof(p); //输出为4, 指针的sizeof都为4, 这个都知道
sizeof(*p); //输出为4,  *p 其实相当于 cc[0], int 的大小是  4, 这个例子也是说明: 批针和数组不一样

struct mystruct {  double a;  char b;  int c;};
sizeof( struct mystruct ); //输出为16, 不是13(8+1+4)
//涉及到对齐, 对齐的概念是struct中各成员各对各的齐, double a 作为开始, 无需对齐; char b, 因为sizeof(char)只占一个字节, 没有什么倍数的概念; 主要是 int c, sizeof(c)是 4, 所以c的开始的位置应该是4的倍数, 而实际开始是 8+1, 是9, 所以需要填充3个字节, 将 int c 放到12开始. 最终内存分配如下:

[a] [a] [a] [a] [a] [a] [a] [a]
[b] [ ] [ ] [ ]
[c] [c] [c] [c]

smithfox | Wednesday 30 March 2011 at 2:54 pm | | system       

One comment

Chanel iPhone 6 Plus Cases

Straight out of the box, one can enjoy basic web surfing and navigation with just the default apps pre-installed on the device. As you might expect, you’ll need to have an Apple ID if you want to download and install more apps from the App Store.

Chanel iPhone 6 Plus Cases, (URL) - 20-04-’15 18:29
(optional field)
(optional field)
为阻止垃圾广告, 请在提交评论前, 回答一个简单问题(Please answer an simple question)
Remember personal info?
Notify
Small print: All html tags except <b> and <i> will be removed from your comment. You can make links by just typing the url or mail-address.