wind7电脑指针

发布时间: 2023-04-17 11:38 阅读: 文章来源:转载
1、情况

c语言指针的指针,还是比较常用的一个功能;当然,我也相信,一些用C语言很长时间的人,也没大用过,因为用不到,这是工作需求决定的,但总体来说,还是经常用的。理解了指针的指针,我感觉才是真正理解了指针的含义

2、定义

指向指针的指针是一种多级间接寻址的形式,或者说是一个指针链。通常,一个指针包含一个变量的地址。当我们定义一个指向指针的指针时,第一个指针包含了第二个指针的地址,第二个指针指向包含实际值的位置。

C 中指向指针的指针一个指向指针的指针变量必须如下声明,即在变量名前放置两个星号。例如,下面声明了一个指向 int 类型指针的指针:int **var;

3、失败的实例1 #include 2 #include 3 #include 4 #include 5 6 void getMemory(char *p, int num)7 {8printf("enter function getMemory\r\n");9printf("p=%p,&p=%p\r\n", p, &p); 10p = (char *)malloc(sizeof(char) * num); 11printf("p=%p,&p=%p\r\n", p, &p); 12printf("exit function getMemory\r\n"); 13 } 14 15 int main() 16 { 17char *str = NULL; 18printf("str=%p,&str=%p\r\n", str, &str); 19getMemory(str, 100); 20strcpy(str, "hello"); 21printf("str=%s\r\n", str); 22printf("str=%p\r\n", str); 23printf("&str=%p\r\n", &str); 24free(str); 25 26 }~ ~"test2.c" 26L, 538C 已写入 root@mkx:~/learn/getMemory# ./test2str=(nil),&str=0x7ffd24ae73c0enter function getMemoryp=(nil),&p=0x7ffd24ae73a8p=0x6a9420,&p=0x7ffd24ae73a8exit function getMemory段错误 (核心已转储)root@mkx:~/learn/getMemory# 4、成功的实例 1 #include 2 #include 3 #include 4 #include 5 6 void getMemory(char **p, int num)7 {8printf("enter function getMemory\r\n");9printf("p=%p,*p=%p\r\n", p, *p); 10*p = (char *)malloc(sizeof(char) * num); 11printf("p=%p,*p=%p\r\n", p, *p); 12printf("exit function getMemory\r\n"); 13 } 14 15 int main() 16 { 17char *str = NULL; 18printf("str=%p, &str=%p\r\n", str, &str); 19getMemory(&str, 100); 20strcpy(str, "hello"); 21printf("str=%s\r\n", str); 22printf("str=%p\r\n", str); 23printf("&str=%p\r\n", &str); 24free(str); 25 26 }~ ~"test1.c" 26L, 542Croot@mkx:~/learn/getMemory# gcc test1.c -o test1root@mkx:~/learn/getMemory# ./test1 str=(nil), &str=0x7ffeddf9e010enter function getMemoryp=0x7ffeddf9e010,*p=(nil)p=0x7ffeddf9e010,*p=0xf22420exit function getMemorystr=hellostr=0xf22420&str=0x7ffeddf9e0105、最后的总结

失败的例子的情况是这样的:

失败就是失败在,传给函数参数的变量p,与当前变量str的地址已经不一样了,它们只是存储的内容是一样的,这就决定了两边的操作,已经没有任何关系了,后来,又给没有分配内存的变量赋值,程序肯定崩溃了

成功的例子情况是这样的:

这里的成功之处,就在于用了指针的指针,一想,感觉有些糊涂的感觉,细想一下,其根本之处在于通过第二级指针,准确的定位到了一级指针,给一级指针赋值了分配内存的地址,就是这么简单。

•••展开全文
相关文章