程序设计基本概念(3)(sizeof)-2.20 2.23

(1)关于sizeof()等若干问题。

求出下列sizeof的返回值。

char* float* int*  ,         都是指针型,所以为4byte。

char s[] = "0123456789", 末尾隐含”\0”,所以为11byte。

char str[100], 为100 byte。

下面的结构体a, 为6byte。

struct a
{
  short a1;
  short a2;
  short a3;
}

下面的结构体b, 为8byte。

struct b
{
  short b1;
  float b2;
}

结构体b的之所为8byte,不是6byte的原因是,系统采用了内存byte对齐的方式来分配内存。

byte对齐的细节要满足3个准则。

1. 结构体变量的首地址能够被结构体中最宽的成员大小能整除。

2. 每个成员相当于首地址的偏移量都是成员大小的整数倍,可以在成员之间填空字节。

3. 结构体的大小应该为最宽成员的整数倍。可在最后填加空字节。

其中补充说明:

void main()
{
int  a1;
int  b1;
int  c1;

printf("0x%08x  ", &a1);
printf("0x%08x  ", &b1);
printf("0x%08x  ", &c1);
}

打印得到的内存地址为

0x001dfc90 

0x001dfc8c 

0x001dfc88

两个变量之间的地址差为4。 内存的地址是按字节来进行管理的。

关于空类的sizeof()

例如

class E
{

};
所占用的字节为1byte. 这是编译器对空类进行实例化的结果。
class A1
{
  int a;
  static int b; 
}

sizeof(A1)所占的字节数位4。因为sizeof计算的是在栈中分配内存的大小。而static的变量存在全局变量区。

(2)sizeof与strlen区别

strlen (http://www.cplusplus.com/reference/cstring/strlen/)

size_t strlen ( const char * str );

Returns the length of the C string str.

The length of a C string is determined by the terminating null-character: A C string is as long as the number of characters between the beginning of the string and the terminating null character (without including the terminating null character itself). This should not be confused with the size of the array that holds the string. For example:
char mystr[100]="test string";
defines an array of characters with a size of 100 chars, but the C string with which mystr has been initialized has a length of only 11 characters. Therefore, while sizeof(mystr) evaluates to 100, strlen(mystr) returns 11.

(3) how many bytes will be occupied for the variable ( int **a[3][4])?

3 x 4 x 4 = 48 byte.

(4) sizeof(string) 在windows 64 + vs2010上是32.

(5) sizeof(class)

1.为类中的非静态成员(static)数据的类型大小之和.

2.有编译器额外加入的成员变量的大小,用来支持语言的某些特性(如:指向虚函数的指针).

3.为了优化存取效率,进行的内存对齐.

4 与类中的构造函数,析构函数以及其他的成员函数无关.

例子:

#include <iostream>
using namespace std;
class a{};
class b{};
class c:public a{
   virtual void fun()=0;
 };
class d:public b,public c{};

int main()
{
   cout<<"sizeof(a)"<<sizeof(a)<<endl;
   cout<<"sizeof(b)"<<sizeof(b)<<endl;
   cout<<"sizeof(c)"<<sizeof(c)<<endl;
   cout<<"sizeof(d)"<<sizeof(d)<<endl;
   return 0;
}

结果是1,1,4,8.其中空类的大小为1,占位用。c的大小为4,包含了虚函数指针。d的大小应该为5,但是结果为了8,因为内存对齐的原因。

class a{
 pivate: 
 int data;
};
 
class b{ 
  private:
  int data;
  static int data1;
};

其中,结果为4,4。static的变量存储在全局变量区。

转载于:https://www.cnblogs.com/bruce81/archive/2013/02/19/2917673.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值