标签:c 指针
指针初步:
#include <stdio.h> int main() { int i = 10; int *p1 = &i; printf("*p1 = %d \n",*p1); } root@ubuntu:~/pointer# gcc main.c ;./a.out *p1 = 10
#include <stdio.h> int main() { int i = 10; int *p1 = NULL; p1 = &i; printf("*p1 = %d \n",*p1); } root@ubuntu:~/pointer# gcc main.c ;./a.out *p1 = 10
#include <stdio.h> int main() { int i = 10; int *p1 = NULL; p1 = &i; *p1 = 20; printf("*p1 = %d \n",*p1); } root@ubuntu:~/pointer# gcc main.c ;./a.out *p1 = 20
野指针
#include <stdio.h> int main() { int *p3 ; //未初始化的指针,野指针, *p3 = 10; //gcc 编译不通过:Segmentation fault (core dumped) } root@ubuntu:~/pointer# gcc main.c Segmentation fault (core dumped)
空指针类型,强转指针
#include <stdio.h> int main() { int i = 10; void *p; p = &i; printf("*p = %d\n",*(int *)p); // (int *)p 把p强转为 int 类型的指针 } root@ubuntu:~/pointer# gcc main.c ;./a.out *p = 10
指针类型兼容,不兼容
#include <stdio.h> int main() { int *p = NULL; unsigned i ; p = &i; char c = ‘a‘; p = &c; } main.c:8:11: warning: assignment from incompatible pointer type [enabled by default] p = &c; ^
数组的地址
#include <stdio.h> int main() { int chunli[10] = {0}; printf("%p\n",chunli); printf("%p\n",&chunli); printf("%p\n",&chunli[0]); printf("%p\n",&chunli[1]); } 数组的名字就是数组的初始地址; root@ubuntu:~/pointer# gcc main.c ;./a.out 0x7fffc53060c0 0x7fffc53060c0 0x7fffc53060c0 0x7fffc53060c4
#include <stdio.h> int main() { int chunli[10] = {2}; int *p1 = &chunli[0]; int *p2 = chunli; printf("%d \n",*p1); printf("%d \n",*p2); } p1 ,p2 指向的是同一个地址 root@ubuntu:~/pointer# gcc main.c ;./a.out 2 2
指针与数组1
#include <stdio.h> int main() { int chunli[10] = {2}; int *p1 = chunli; printf("sizeof(chunli) =%ld \n",sizeof(chunli)); printf("sizeof(p1) =%ld \n",sizeof(p1)); } // 32bit系统 一个指针占用4个字节 // 64bit系统 一个指针占用8个字节 root@ubuntu:~/pointer# gcc main.c ;./a.out sizeof(chunli) =40 sizeof(p1) =8
本文出自 “魂斗罗” 博客,请务必保留此出处http://990487026.blog.51cto.com/10133282/1772393
标签:c 指针
原文地址:http://990487026.blog.51cto.com/10133282/1772393