注:平台是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字节
}
可以对数组元素赋值,不能对数组名赋值
<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的不是字符串,而是此字符串中的第一个元素的地址
指针初始化:
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);
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];