c - 让两个指针指向同一个内存块的正确方法

标签 c pointers memory memory-management allocation

我有一个结构:

struct generic_attribute{
    int current_value;
    int previous_value;
};

还有一个构造函数输出指向这个结构的指针:

struct generic_attribute* construct_generic_attribute(int current_value){
    struct generic_attribute *ga_ptr;
    ga_ptr = malloc (sizeof (struct generic_attribute));
    ga_ptr->current_value = current_value;
    ga_ptr->previous_value = 0;
    return ga_ptr;
}

现在,在另一个函数中,我想定义一个指针并将其设置为指向与上述构造函数输出的指针相同的地址。

struct tagged_attribute* construct_tagged_attribute(int num_args, int *args){
    ...
    struct generic_attribute* generic = malloc (sizeof(struct generic_attribute));
    generic = construct_generic_attribute(args[0]);
    ...
}

在我看来,我在这里做的是这样的:

1) 我定义了一个“generic”指针并分配一个内存块来保存 generic_attribute 结构的一个实例。

2) 我在其中调用一个函数 construct_generic_attribute,程序再次分配一个 generic_attribute 结构大小的内存块。它输出指向该内存块的指针。

3) 在 construct_tagged_attribute 中,我将“generic”指针设置为等于 construct_generic_attribute 函数输出的指针,所以现在它们都指向同一个内存槽。

但是,我分配的内存似乎是我需要分配的内存的两倍。

有没有办法让我只分配一次内存,而不会因为未能为“通用”指针分配空间而出现段错误?或者,我是否误解了这段代码中发生的事情?

最佳答案

struct generic_attribute* generic = construct_generic_attribute(args[0]);

应该可以解决问题。指针变量就是一个变量。您可以像交换数字一样交换指针值。

关于c - 让两个指针指向同一个内存块的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31103819/

相关文章:

c - 更快地交换结构数组中的元素

时间:2018-01-08 标签:c++oop: function pointer table

c - 如何根据条件对 void 指针进行类型转换?

c - 我无法在从函数返回的 char 指针上使用 free()

C 不确定要正确释放什么

c - 关于结构体指针及其工作原理

c - 在C中读取文件并拆分字符串

calloc() 比 malloc() 和 memset() 慢

c - 初始化二维数组时出现段错误

c - 最大限度地减少 sscanf 的内存消耗