简体   繁体   English

结构的初始化函数(即“构造函数”),为什么变量未正确初始化?

[英]Initialization function (i.e. “constructor”) for struct, why are variables not being initialized properly?

I have an unnamed structure called `FooStruct', and I wrote a function for it that initializes all its variables and also takes care of dynamic memory allocation. 我有一个名为“ FooStruct”的未命名结构,我为此编写了一个函数,该函数初始化其所有变量,并负责动态内存分配。

I tried running this code, but it is not producing the results that I am expecting. 我尝试运行此代码,但未产生预期的结果。 For some reason, the variables are initialized correctly when inside the function, but then they change again once the block is exited. 由于某些原因,变量在函数内部时已正确初始化,但是一旦退出该块,它们便会再次更改。

A project that I'm working on requires that I use unnamed structs only. 我正在处理的项目要求仅使用未命名的结构。 Why is this happening? 为什么会这样呢?

#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int fooPrimitive;
} FooStruct;

void FooStructInit(FooStruct * ptr, int num) {
    ptr = (FooStruct*)malloc(sizeof(FooStruct));
    ptr -> fooPrimitive = num;

    // Expected output: 5
    // Actual output: 5
    printf("ptr -> fooPrimitive: %d\n", (ptr -> fooPrimitive));
}

int main() {
    FooStruct * ptr;
    FooStructInit(ptr, 5);

    // Expected output: 5
    // Actual output: some random number
    printf("FooStruct -> fooPrimitive: %d\n", (ptr -> fooPrimitive));
}

When you pass ptr to FooStructInit , it is copied and this copy is assigned the return value of malloc then. 当将ptr传递给FooStructInit ,它将被复制,然后为该副本分配malloc的返回值。 This is called pass-by-value . 这称为传递值 Instead, pass a pointer to ptr to actually write to ptr and not just the passed argument: 而是传递指向ptr的指针以实际写入ptr ,而不仅仅是传递的参数:

void FooStructInit(FooStruct** ptr, int num) {
    *ptr = malloc(sizeof(FooStruct));
    (*ptr)->fooPrimitive = num;

    // Expected output: 5
    // Actual output: 5
    printf("(*ptr)->fooPrimitive: %d\n", ((*ptr)->fooPrimitive));
}

int main() {
    FooStruct* ptr;
    FooStructInit(&ptr, 5);

    // Expected output: 5
    // Actual output: 5
    printf("FooStruct->fooPrimitive: %d\n", (ptr->fooPrimitive));
}

Notes: 笔记:

C only has pass by value semantics, so when you pass a pointer to a function, the original value of the pointer is not changed, only the local copy is changed in the function. C仅具有按值传递语义,因此,当您将指针传递给函数时,指针的原始值不会更改,而只会在函数中更改本地副本。

The way to get around this is to pass a pointer to a pointer, so that you can change the value at the original memory location. 解决此问题的方法是将一个指针传递给一个指针,以便您可以更改原始存储位置的值。

void FooStructInit(FooStruct **ptr, int num) {
    *ptr = malloc(sizeof(FooStruct));
    ...
}

int main(void) {
    FooStruct * ptr;
    FooStructInit(&ptr, 5); /* get the address of the pointer */
    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM