C 语言指针的用法
1.指针基本介绍
#include <stdio.h> #include <stdlib.h> #include <stdint.h> int main() { int a = 10; int *pa = &a; printf("%d\n", *pa); int32_t *intP = (int32_t *) malloc(4); *intP = 100; printf("%d\n", *intP); int32_t *intPo = (int32_t *) malloc(4); intPo[0] = 101; printf("%d\n", *intPo); int len = 10; int32_t *intPoi = (int32_t *) malloc(len * sizeof(int32_t)); intPoi[0] = 102; intPoi[1] = 103; printf("%d\n", intPoi[1]); printf("%d\n", *(intPoi + 1)); free(intPoi); char *str = "Hello"; printf("%ld\n", sizeof(str));//指针长度 64位 8 32位 4 int64_t poin = (int64_t) str;//int64_t和指针相互转换 JNI(Java Native Interface) Java long==C int64_t char *str1 = (char *) poin; printf("%s\n", str1); return 0; }
2.函数指针
#include <stdio.h> void hello(){ printf("Hello World!\n"); } //自定义 typedef void (*SimpleFunc)(); int main() { //常规方式 hello(); //函数指针 void (*fp)() = &hello; fp(); //自定义 SimpleFunc simpleFunc = &hello; simpleFunc(); return 0; }
3.无类型指针
#include <stdio.h> #include <stdlib.h> int main() { //无类型指针 void *data = "Hello C"; printf("%s\n", data); void *a = malloc(8); printf("%ld\n", sizeof(a[0]));//无类型指针的访问单元 1字节 void *b = malloc(8); int *intb = b; printf("%ld\n", sizeof(intb[0]));//指定类型后 变成4字节 intb[0] = 10000; printf("%d\n", intb[0]); free(b); void *c = 10000; printf("%d\n", c); return 0; }