C_指针的定义与使用(学习笔记)

1.

char *p = (char *)malloc(100)

//声明了一个字符指针p,并初始化为堆上的一个地址(剩下的99个字节内存都可由p访问)

char *str = "Hello world"

//str为字符串首地址

NULL是个常量

viod * 是无类型指针

2. * 解引用运算符(dereference)

char a[10]={1,2,3};

char *s = "Hello world";//存在了静态常量里

*arr = 100; //成功把a[0]改成100

*s = 'X'; //不行!!非法访问静态常量

3.指针类型相互转换:

sizeif(p) = 4 or 8

sizeof(*p) = 所指向类型长度

char *c;

int p* = (int *)&c;

或char *p2 = (cahr *)p1;

p2只能访问第一个字节的内存里的东西。

指针类型转换的一个实用案例:

char* buf = (char  *)malloc(16);

*(int *)buf = 123;

printf("%d",*(int *)buf); 

4.void *p

猜你喜欢

转载自blog.csdn.net/midi_of_gyk/article/details/80825141