c - C中的单指针与双指针
问题描述
已经在这里提出了这个问题: 双指针与单指针
我按照上述问题的说明进行操作,但遇到了段错误,仍然无法准确理解内存中发生的事情(什么指向什么以及如何)。下面是代码:
#include <stdio.h>
#include <stdlib.h>
void func(int **ptr)
{
*ptr = (int *) malloc (sizeof(int));
**ptr = 10;
printf("Inside func: ptr: %p *ptr: %p **ptr: %p %d\n", ptr, *ptr, **ptr, **ptr);
}
void func2(int *ptr)
{
int i = 10;
ptr = (int *) malloc (sizeof(int));
*ptr = 288;
printf("Inside func2: ptr: %p *ptr: %p %d\n", ptr, *ptr, *ptr);
}
int main()
{
int *a = NULL, *b = NULL;
func(&a);
printf("&a: %p, a: %p, *a: %p *a: %p %d\n", &a, a, *a, *a, *a);
func2(b);
printf("*b: %d\n", *b);
return 0;
}
输出:
main.c:8:51: warning: format ‘%p’ expects argument of type ‘void *’, but argument 4 has type ‘int’ [-Wformat=]
main.c:16:42: warning: format ‘%p’ expects argument of type ‘void *’, but argument 3 has type ‘int’ [-Wformat=]
main.c:23:33: warning: format ‘%p’ expects argument of type ‘void *’, but argument 4 has type ‘int’ [-Wformat=]
main.c:23:40: warning: format ‘%p’ expects argument of type ‘void *’, but argument 5 has type ‘int’ [-Wformat=]
Inside func: ptr: 0x7ffcf5c49760 *ptr: 0x22f7010 **ptr: 0xa 10
&a: 0x7ffcf5c49760, a: 0x22f7010, *a: 0xa *a: 0xa 10
Inside func2: ptr: 0x22f7030 *ptr: 0x120 288
Segmentation fault (core dumped)
在 func--> 何时a & ptr
分配并指向相同的内存位置,为什么它不能发生在 func2 中。无论如何,对于 *ptr,我正在传递 b(这是 *b 的地址)并更改值。
无法理解什么指向什么以及如何。如果有人可以提供帮助将非常感激。
尽管它重复了已经提出的问题,但由于答案不足以让我理解,因此已发布。因此,在正确回答问题之前,请不要将其标记为重复。
解决方案
指针b
从未初始化,不在 main 中,也不在函数中。它不指向任何有效的内存块。
您可以尝试以下方法。&b 是指向整数的指针。
int b = 0;
func2(&b);