一、请写出下列程序的运行结果
int main(int argc, char* argv[])
{
char string[]=" 1235678";
char *p = string;
void *p1;
int n=318;
int size;
size = sizeof(string); //1
printf( "%d\n", size);
size = sizeof(p);//2
printf( "%d\n", size);
size = sizeof(n);//3
printf( "%d\n", size);
p1=malloc(14);
size = sizeof(p1);//4
printf( "%d\n", size);
return 0;
}
运行结果为:9
8
4
8
1)第一个printf:string是数组的名字,它的大小就是整个数组的大小,字符串中有八个字符,再加上‘\0’,所以的值为9.
2)第二个printf:p是指针变量,它的大小与操作系统的位数有关,64位是八个字节,32位是4个字节。附加:*p指数组中的第一个字符,sizeof(*p)== 1;
3)第三个printf:n是整型数据,它的大小占四个字节。
4)第三个printf:p1是指针变量,与p相同。
二、数组在函数中传递
linux下,32位:
void func(char str[])
{
printf("%d\n",sizeof(str));
}
int main()
{
char str[100];
func(str);
printf("%d",sizeof(str));
getchar();
return 0;
}
运行结果 4 100
函数传递时,传递的是地址,即指针,指针的大小与操作系统有关,32位 指针占4个字节
三、共用体和结构体
#include <stdio.h>
#include <stdlib.h>
typedef union {
long i;
int a[5];
char k;
}date;//20
typedef struct {
double cat;
date dog;//20
}car;
int main()
{
double l;
printf("%d\n%d\n%d\n", sizeof(car),sizeof(date),sizeof(car)+sizeof(date));
getchar();
return 0;
}
运行结果:
32
20
52
共用体的大小根据所定义的变量中最大的一个决定,所以sizeof(date) 是4个int的大小即20个字节
结构体的大小时所有变量的大小的总和,所以是8+20,但是后面的占用大小要与前面的8对齐所以20需要多加4
个字节,所以总大小是32.还有一种说法是结构体中最宽的是double类型,即是8,总大小需要时八的倍数,28增加4才是八的倍数,所以是32
四、结构体引用自身
#include <stdio.h>
struct node{
int num;
float data;
struct node node1;
};
int main()
{
printf("%d\n",sizeof(struct node));
return 0;
}
运行错误,因为结构体里面包括自身,形成了嵌套死循环。
然而下面情况则不同
#include <stdio.h>
struct node{
int num;
float data;
struct node *next;
};
int main()
{
printf("%d\n",sizeof(struct node));
return 0;
}
输出 12
结构体里面,第一个是整型,占四个字节,第二个是浮点型,占四个字节,而第三个,在32位机子上指针占四个字节,所以最后结构体的总大小是12.
五、结构体里面有函数
#include <iostream>
#include <stdlib.h>
using namespace std;
struct mystr
{
int a;
int b;
void go()
{
cout<<"1234567"<<endl;
}
};
int main()
{
cout<<sizeof(mystr);//8
return 0;
}
结构体长度为8,函数在代码区,代码区是公用的,c++把函数跳过,代码区的函数不计入sizeof
六、有关引用
#include <iostream>
#include <stdlib.h>
using namespace std;
struct mystr1
{
int a;
int b;
char &c;
};
struct mystr2
{
char &a;
char &b;
char &c;
};
struct mystr3
{
char a;
char b;
char c;
};
int main()
{
int num = 10;
int &rnum(num);
cout<<sizeof(rnum)<<endl;//4
double db = 10.9;
double &rdb(db);
cout<<sizeof(rdb)<<endl;//8
cout<<sizeof(mystr1)<<endl;//12
cout<<sizeof(mystr2)<<endl;//12
cout<<sizeof(mystr3)<<endl;//3
return 0;
}
引用本质上是指针,直接sizeof引用,就是求引用的数据的大小,引用变量占4个字节。
在mystr2中,三个char类型的引用,相当于三个指针,32位指针占四个字节。