C语言进阶课程学习记录-第27课 - 数组的本质分析
- 数组
- 实验-数组元素个数的指定
- 实验-数组地址与数组首元素地址
- 实验-指针与数组地址的区别
- 小结
本文学习自狄泰软件学院 唐佐林老师的 C语言进阶课程,图片全部来源于课程PPT,仅用于个人学习记录
数组
实验-数组元素个数的指定
#include <stdio.h>
int main()
{
int a[5] = {1, 2};
int b[] = {1, 2};
int c[5] = {0};
printf("a[2] = %d\n", a[2]);
printf("a[3] = %d\n", a[3]);
printf("a[4] = %d\n", a[4]);
printf("sizeof(a) = %d\n", sizeof(a));
printf("sizeof(b) = %d\n", sizeof(b));
printf("count for a: %d\n", sizeof(a)/sizeof(int));
printf("count for b: %d\n", sizeof(b)/sizeof(int));
printf("c[0] = %d\n", c[0]);
printf("c[1] = %d\n", c[1]);
printf("c[2] = %d\n", c[2]);
printf("c[3] = %d\n", c[3]);
printf("c[4] = %d\n", c[4]);
return 0;
}
/*
output:
a[2] = 0
a[3] = 0
a[4] = 0
sizeof(a) = 20
sizeof(b) = 8
count for a: 5
count for b: 2
c[0] = 0
c[1] = 0
c[2] = 0
c[3] = 0
c[4] = 0
*/
实验-数组地址与数组首元素地址
#include <stdio.h>
int main()
{
int a[5] = { 0 };
printf("a = %p\n", a);
printf("&a = %p\n", &a);
printf("&a[0] = %p\n", &a[0]);
return 0;
}
/*
output:
a = 0060FEEC
&a = 0060FEEC
&a[0] = 0060FEEC
*/
实验-指针与数组地址的区别
#include <stdio.h>
int main()
{
int a[5] = {0};
int b[2];
int* p = NULL;
p = a;
printf("a = %p\n", a);
printf("p = %p\n", p);
printf("&p = %p\n", &p);
printf("sizeof(a) = %d\n", sizeof(a));
printf("sizeof(p) = %d\n", sizeof(p));
printf("\n");
p = b;
printf("b = %p\n", b);
printf("p = %p\n", p);
printf("&p = %p\n", &p);
printf("sizeof(b) = %d\n", sizeof(b));
printf("sizeof(p) = %d\n", sizeof(p));
//b = a;//error: incompatible types when assigning to type 'int[2]' from type 'int *'|
return 0;
}
/*
output:
a = 0060FEEC
p = 0060FEEC
&p = 0060FEE0
sizeof(a) = 20
sizeof(p) = 4
b = 0060FEE4
p = 0060FEE4
&p = 0060FEE0
sizeof(b) = 8
sizeof(p) = 4
*/
小结
数组是一片连续的内存空间
数组的地址和数组首元素的地址意义不同
数组名在大多数情况下被当成指针常量处理
数组名其实并不是指针,不能将其等同于指针