int *a; //整型指针
char *b; //字符型指针
float *c; //浮点型指针
struct A *d;//特殊类型指针
- 虽然指针的类型有很多,但指针的大小是固定的(和编译器有关)一般有32和64位即4个字节或8个字节。在64位的编译其中,指针所占用的空间即为64位。一般情况下指针和int类型占有相同的空间,所以指针和int类型可以相互转换
int *a; //整型指针
char *b; //字符型指针
float *c; //浮点型指针
struct A *d;//特殊类型指针
printf("%d, %d, %d, %d, %d\n", sizeof(a), sizeof(b), sizeof(c), sizeof(d), sizeof(int));//打印结果为 4,4,4,4,4(假设编译器为32位的)
- 指针可以指向任何地方:如变量,函数,参数,所有程序中的东西,甚至系统中任何地方如内存地址,硬件设备(打印机,摄像头)等
- 指针移动的步长为指针所指向的数据类型所占用的内存大小
char buf[1024];
char *a = buf;
int *b = (int *)buf;
a += 8;
b += 2;
if((int)a == (int)b) {//指针转换成整数
printf("a == b, %u == %u\n", (int)a, (int)b); //此部分会被打印出来
}
*b = 0x01020304;
printf("%d, %d, %d, %d\n", *a, *(a + 1), *(a + 2), *(a + 3)); //会打印4,3,2,1(假设整型数据低字节排序)
char buf[1024];
char *a = buf;
int *b = (int *)buf;
a += 8; b += 2;
if((int)a == (int)b)
{
printf("a == b\n"); //此部分会被打印出来
}
if((int)(buf + 8) == (int)b) {
printf("buf + 8 == b, %08x == %08x\n", (int)(buf + 8), (int)b); //此部分会被打印出来
}
*b = 0x01020304;
printf("%d, %d, %d, %d\n", *a, *(a + 1), *(a + 2), *(a + 3)); //会打印4,3,2,1(假设整型数据低字节排序)
printf("%d, %d, %d, %d\n", buf[8], buf[8 + 1], buf[8 + 2], buf[8 + 3]); //会打印4,3,2,1(假设整型数据低字节排序)
printf("%d, %d, %d, %d\n", *(buf + 8), *(buf + 8 + 1), *(buf + 8 + 2), *(buf + 8 + 3)); //会打印4,3,2,1(假设整型数据低字节排序)
int *c = (int *)a;
printf("0x%08X\n", *c); //会打印0x01020304(假设整型数据低字节排序)
- 字符串是数组:元素为字符且以‘\0’为结尾。待续
- example.c
#include <stdio.h>
#include <string.h>
#define printf(format, arg...) fprintf(stdout, "%s, "format, __FUNCTION__, ##arg)
void testPointSize() {
int *a; //整型指针
char *b; //字符型指针
float *c; //浮点型指针
struct A *d;//特殊类型指针
printf("%d, %d, %d, %d\n", sizeof(a), sizeof(b), sizeof(c), sizeof(d));//打印结果为 4,4,4,4(假设编译器为32位的)
}
void testString() { //本函数只做测试,实际上是很危险的
int test(char s[]) { //这么写不知到会不会被人打死
char a[13];
strcpy(s, "hello");
printf("%d, %d, %d, %d\n", sizeof(s), sizeof(a), strlen(s), strlen(a)); //可以看出,数组做形参时是没有实际大小的,打印出的是指针的大小4
return 0;
};
char a[12];// = {0};// = "ld";
int a1;
printf("%d, %d\n", strlen(a), a1);
test(a);
printf("%d\n", strlen(a));
}
void testPoint() {
char buf[1024];
char *a = buf;
int *b = (int *)buf;
a += 8;
b += 2;
if((int)a == (int)b) {
printf("a == b\n"); //此部分会被打印出来
}
if((int)(buf + 8) == (int)b) {
printf("buf + 8 == b\n"); //此部分会被打印出来
}
*b = 0x01020304;
printf("%d, %d, %d, %d\n", *a, *(a + 1), *(a + 2), *(a + 3)); //会打印4,3,2,1(假设整型数据低字节排序)
printf("%d, %d, %d, %d\n", *(buf + 8), *(buf + 8 + 1), *(buf + 8 + 2), *(buf + 8 + 3)); //会打印4,3,2,1(假设整型数据低字节排序)
}
int main() {
testString();
//testPointSize();
//testPoint();
return 0;
}