C 语言学习:使用寻址运算符

程序中的变量会占用一定量的内存,不同变量占用的类存大小(字节)不同,今天学习计算变量类型占用内存量的方法以及如何获得不同变量在内存中的地址。

获取 Int,Double 变量地址

1.1 程序 mem_addr.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/*Program: mem_addr.c*/
#include <stdio.h>

int main(void)
{
/*declare some integer variables*/
long a=1L;
long b=2L;
long c=3L;
int g=4;

/*declare some floating-point variables */
double d=4.0;
double e=5.0;
double f=6.0;

printf("A varible of type long occupies %d byte.",sizeof(long));
printf("nHere are the addresses of some variables of type long:");
printf("nThe address of a is :%p, The address of b is :%p",&a,&b);
printf("nThe address of c is :%p",&c);
printf("nnA varible of type double occupies %d bytes.", sizeof(double));
printf("nHere are the addresses of somae varibles of type double:");
printf("nThe address of d is :%p, The address of e is :%p",&d,&e);
printf("nThe address of f is :%p",&f);
printf("nnA varible of type int occupies %d bytes.n", sizeof(int));

return 0;
}

1.2 编译 mem_addr.c

1
[pg92@redhatB array]$ gcc -o mem_addr mem_addr.c

1.3 执行 mem_addr.c

1
2
3
4
5
6
7
8
9
10
11
12
[pg92@redhatB array]$ ./mem_addr
A varible of type long occupies 4 byte.
Here are the addresses of some variables of type long:
The address of a is :0xbfe26418, The address of b is :0xbfe26414
The address of c is :0xbfe26410

A varible of type double occupies 8 bytes.
Here are the addresses of somae varibles of type double:
The address of d is :0xbfe26408, The address of e is :0xbfe26400
The address of f is :0xbfe263f8

A varible of type int occupies 4 bytes.

备注: long int 类型占用的字节为 4,并且输出了变量 a,b,c 在内存中的地址;
double 类型占用的字节为 8,并且输出了变量 d,e,f 在内存中的地址。

获取数组变量地址

2.1 array_addr.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/*Program: array_addr.c*/

#include <stdio.h>

int main(void)
{
int numbers[5];
int i=0;

for(;i<5;i++)
{
numbers[i]=12*(i+1);
printf("n numbers[%d] Address: %p Contents: %d",i,&numbers[i],numbers[i]);
}
return 0;
}

2.2 编译 array_addr.c

1
[pg92@redhatB array]$ gcc -o array_addr array_addr.c

2.3执行 array_addr

[pg92@redhatB array]$ ./array_addr
numbers[0] Address: 0xbfe4f3f8 Contents: 12
numbers[1] Address: 0xbfe4f3fc Contents: 24
numbers[2] Address: 0xbfe4f400 Contents: 36
numbers[3] Address: 0xbfe4f404 Contents: 48
numbers[4] Address: 0xbfe4f408 Contents: 60

备注:可以看出每个元素的地址都要比前一个元地址多 4,因为 int 类型变量在内存中占用四个节字。

原创文章,作者:kirin,如若转载,请注明出处:https://blog.ytso.com/tech/database/237935.html

(0)
上一篇 2022年1月29日 22:31
下一篇 2022年1月29日 22:31

相关推荐

发表回复

登录后才能评论