指针与const
1 #include <stdio.h> 2 #include <string.h> 3 4 typedef struct node 5 { 6 int next; 7 int data; 8 }*Node; 9 10 void modify(Node l) 11 { 12 printf("l = %d, &l = %u\n",l,&l); 13 l->data = 1; 14 l->next = 1; 15 (*l).data = 10; 16 (*l).next = 100; 17 } 18 19 Node MM(Node l) 20 { 21 l = new node; 22 l->data = 2; 23 l->next = 2; 24 return l; 25 } 26 27 void M(Node *l) //二维指针 28 { 29 (*l) = new node; 30 (*l)->data = 12; 31 (*l)->next = 12; 32 } 33 void fun1(char *pa) //相当于传值 34 { 35 //相当与char *tmp = pa; 36 printf("&pa = %u pa %d pa = %s\n", &pa, pa,pa); 37 pa = "ni,mei"; //只是更改了tmp的值 38 printf("%u %d %s\n", &pa, pa,pa); 39 } 40 41 void fun2(char **pa) //传递pa的地址 42 { 43 *pa = "nimie"; //指向pa char *指针 44 } 45 46 void int1(int *p) 47 { 48 *p = 100; 49 50 } 51 52 int main( ) 53 { 54 //下面这个等价 55 const char *p; 56 char const *q; 57 // "hello" 为字符串常量 const char [5] 58 char *c1 = "hello"; 59 char *tt; 60 tt = c1; 61 // tt为char *指针 62 // *tt 为char 指向内存单位为tt的第一个字符 63 tt = "wawa"; 64 char *const l = tt; //对与这种只能在初始化时赋值 65 const char * const m = "haha"; //指向const对象的const指针 66 char c2[20] = "world"; 67 char c3[15]; 68 // 不能这样赋值, c3 = "haha", 69 p = c1; 70 q = c2; 71 printf("%s\n%s\n%s\n%s\n",p,q,m,l); 72 73 int st = 10; 74 int *pp = &st; 75 printf("int %u %d\n",pp, *pp); 76 77 char *pa = "now"; 78 printf("&pa = %u pa = %d %s\n",&pa, pa, pa); 79 printf("函数1:\n"); 80 printf("修改之前:%s\n",pa); 81 fun1(pa); //这里相当于值传递 82 printf("修改之后:%s\n", pa); 83 84 printf("函数2:\n"); 85 printf("修改之前:%s\n",pa); 86 fun2(&pa); 87 printf("修改之后:%s\n", pa); 88 89 Node ps = new node; 90 printf("ps = %d, &ps = %d\n",ps,&ps); 91 /* ps 只是一个指向Node的指针,没有申请内存 92 ps->data = 2; 93 ps->next = 2; 94 */ 95 printf("%d %d\n",ps->data,ps->next); 96 modify(ps); 97 printf("%d %d\n",ps->data,ps->next); 98 99 Node pq; 100 //printf("%d %d\n",ps->data,ps->next); 101 pq = MM(pq); 102 printf("%d %d\n",pq->data,pq->next); 103 104 //需要用二维指针 105 Node pl; 106 M(&pl); 107 printf("%d %d\n",pl->data,pl->next); 108 109 int *ll = &st; 110 printf("ll = %d\n",*ll); 111 int1(ll); 112 printf("ll = %d\n",*ll); 113 return 0; 114 }