Writing init function for C struct

后端 未结 2 385
攒了一身酷
攒了一身酷 2021-01-21 18:02

So this is my struct in a header file:

struct _Variable {
    char *variableName;
    char *arrayOfElements;
    int32_t address;
};
typedef struct _Variable Var         


        
相关标签:
2条回答
  • 2021-01-21 18:27

    You should pass &variable1 to your method. Operator & will take the address of your struct and that is what you need to assign to the pointer on variable.

    Use:

    Variable var1;
    

    And then call the method:

    initVariable(&var1, "variable1", "1, 2, 3", 4);
    
    0 讨论(0)
  • 2021-01-21 18:48
    Variable *variable1;
    

    gives you an uninitialised pointer. You don't own the memory it points to so can't safely write to it.

    You need to allocate storage for variable1

    Variable variable1;
    initVariable(&variable1, "variable1", "1, 2, 3", 4);
    

    would work.

    If you want variable1 to be dynamically allocated, it'd be easiest to have initVariable handle this

    Variable* initVariable(char *variableName, char *arrayOfElements, int32_t address)
    {
        Variable* var = malloc(sizeof(*var));
        if (var != NULL) {
            var->variableName = strdup(variableName);
            var->arrayOfElements = strdup(arrayOfElements);
            var->address = address;
        }
        return var;
    }
    

    Note that I've also simplified allocation/population of strings here. Your code works but if you're using a posix-compatible system, strdup is a much simpler way to achieve the same results.

    As discussed in comments, you don't need to allocate storage if the string members of Variable will all be string literals. In this case, you could simplify things to

    Variable* initVariable(char *variableName, char *arrayOfElements, int32_t address)
    {
        Variable* var = malloc(sizeof(*var));
        if (var != NULL) {
            var->variableName = variableName;
            var->arrayOfElements = arrayOfElements;
            var->address = address;
        }
        return var;
    }
    
    0 讨论(0)
提交回复
热议问题