指针和内存知多少

 1 #include
 2 #include
 3 #include
 4 
 5 void mmcpy(char *p)
 6 {
 7     printf("分配前 %x
",p);  //p=st,两个指针变量都保持同一个地址
 8     p = (char *)malloc(100);
 9   //p = (char *)0x383138;    //p=0x383138,指向了这地址,从此和st无关系了
10     printf("分配后 %x
",p);
11 }
12 
13 int main(void)
14 {
15     char ds='a';
16     char *st=&ds; //注意这样是错误的哦:char *st=ds;
17 
18     printf("调用前 %x
",st);
19     mmcpy(st);
20     printf("调用后 %x
",st);
21     
22   //strcpy(st, "hello");
23     strcpy((char *)0x383138, "hello"); //"hello"占据6个字节的空间,别忘了''
24   //printf("%s
",st);
25     printf("%s
",(char *)0x383138);
26 
27     return 0;
28 }

//指针也是个变量,里面保持的是地址,你给它赋另一个地址,他就指向另一个地址。它不认主人的
//虽然各个指针间赋值,但是各个指针之间没有必然的联系,是独立的。
//只是相互赋值的指针都指向了同一个地址而已

改进1:

 1 #include //printf
 2 #include //malloc,free
 3 #include //strcpy
 4 
 5 char* mmcpy(char *p)
 6 {
 7     p = (char *)malloc(100);
 8     return p;
 9 }
10 
11 int main(void)
12 {
13     char *st=NULL;
14 
15     st=mmcpy(st);
16     if (st == NULL) //是否成功分配
17         return (-1);
18     strcpy(st, "hello");
19     printf("%s
",st);
20     
21     free(st); //malloc后free,好习惯,必须的
22     
23     return 0;
24 }

改进2:

 1 #include
 2 #include
 3 #include
 4 
 5 void mmcpy(char **p)
 6 {
 7     *p=(char *)malloc(100);
 8 }
 9 
10 int main(void)
11 {
12     char *st=NULL;
13 
14     mmcpy(&st);
15     if (st==NULL)
16         return (-1);
17         
18     strcpy(st, "hello");
19     printf("%s
",st);
20 
21     free(st);
22 
23     return 0;
24 }
原文地址:https://www.cnblogs.com/eustoma/p/6664502.html