数组与指针

注:平台是Centos 7.2,使用的编译器为gcc 4.8.5


(1)构成。

数组由若干个元素组成,它的大小是sizeof(a),指针变量中放的是地址,char *p,int  *p,float *p,double *p,在存储是都占8个字节(VC,DEV中指针变量为4字节,与编译器默认值有关)

#include<stdio.h>

void main()
{
	char a[] = {1, 2, 3};
	char* p = a;
	int* pc = NULL;
	float* pf = NULL;
	double* pd = NULL;
	printf("%d ", sizeof(a));<span>	</span>// 3字节
	printf("%d ", sizeof(p));<span>	</span>// 8字节
	printf("%d ", sizeof(pc));<span>	</span>// 8字节
	printf("%d ", sizeof(pf));<span>	</span>// 8字节
	printf("%d ", sizeof(pd));<span>	</span>// 8字节
}


(2)赋值

可以对数组元素赋值,不能对数组名赋值

<span></span><pre name="code" class="objc">
 
	char str[15];  	
	str[0] = 'h';		//对数组元素赋值,合法
	str = "hello word";<span style="font-family: Arial, Helvetica, sans-serif;">     //数组名是常量,不能被赋值,非法。数组名代表一个固定值(数组首元素地址),不能被赋值或改变</span>
	char* a = NULL;
	a = "hello word";	//将字符串首元素地址赋值给指针变量,合法。赋值给a的不是字符串,而是此字符串中的第一个元素的地址


(3)初始化。

指针初始化:

char* p = "hello word";	//定义字符指针变量p,并把字符串第一个元素的地址赋给p

等价于

char* p;
p = "hello word";<pre name="code" class="html">
 


数组初始化:

char str[15] = "hello word";<span>	</span>//定义字符数组str,并把字符串赋给数组中个元素<pre name="code" class="html">

 不等价于 

char str[15];
str = "hello word";<span>	</span>//将字符串赋值给str[0],类型不兼容,非法。


(4)指针变量的值可以改变

char *p = "hello word"; 
p = p + 6;<span>		</span>//改变指针变量的值,即改变指针变量的指向
printf("%s\n",p);<span>	</span>//输出从p指向的字符开始的字符串
运行结果

word
而下面这个是错的:

char str[] = "hello word";
str = str +6;<span>			</span>//<span style="font-family: Arial, Helvetica, sans-serif;">数组名代表一个固定值(数组首元素地址),不能被赋值或改变</span>
printf("%s\n",str);


(5)类型
int a[3];
int b[3][3];
a为数组首元素的地址,但并不是数组的起始地址,&a为整个数组的地址,a的类型为int[3];

a+1  等价于  (unsigned int)a + sizeof(*a)

&a + 1  等价于 (unsigned int)(&a) + sizeof(*&a)

b是指向数组的指针,类型为char(*)[3], &b[0][0] 等价于b[0];


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值