数组和指针
1. 数组首地址
对于char a[] = "linux";其中
a:数组首地址;
&a:数组地址;
&(a[0]):数组首元素地址。
在数值上,三者都相等,但表示的意义却不同。如:
a+1 == a+1*sizeof(char) //加元素所占字节
(&a)+1 == a+1*sizeof(a) //加数组所占字节
&(a[0])+1 == a+1*sizeof(char) //加元素所占字节
2. 数组传参
数组名作为实参传递时,实际传递的是数组首元素地址。
intmain(void)
{
int b[] ={1,2,3,4,5};
fanc(b);
printf("%d",sizeof(a));
return 0;
}
int fanc(inta[])
{
printf("%d\n",sizeof(a));
}
上述程序输出为4 6。
注:在主函数中求数组元素个数可用下面的语句:
sizeof(b)/sizeof(b[0]);
或者若知道数组类型也可以用:
sizeof(b)/sizeof(int);
等
3. 定义而无初始化的指针为野指针。如:
int *p;
*p =5;
由于野指针指向不可知,未避免程序崩溃,应该避免出现野指针。
① int a = 5; int *p = &a;
② 定义指针同时初始化: int *p = NULL;
③ 使用完后重置为NULL
④ 操作一个指针前先检查是否为NULL:if(NULL != p){}
4. 函数指针(指向函数的指针)
int(*pfuc)(void)
int * func(void)
int(*func[4])(void)
5.
各种存储类型和特性
6.
进程内存映像
各变量分配情况,引用例:
int a = 0; //全局初始化区
char *p1; //全局未初始化区,程序运行自初始化为0
int main(void)
{
intb; //栈
char s[] = "abc"; //栈
char *p2; //栈
char *p3="123456";//123456\0在代码段上,p3在栈上。
static int c = 0; //全局(静态)初始化区
p1= (char *)malloc(10); //分到的10字节在堆区
strcpy(p1,"123456");//123456\0在代码段,编译器可能会将其与p3所指优化为一个地方
return 0;
}
char *cp = "hello";
char *p = (char *)malloc(10);
p=cp;
7. 强制转换访问特定地址:
int *p = (int *)0x30000000;
8.
使用union来测试机器的大小端模式
Typedef union endian
{
char a;
int b;
}endian;
int islend(void)
{
endian e;
e.b = 1;
return (e.a == 1); // return 1 -> little endian
// return 0 -> big endian
}
date:2013-01-24~2013-01-25