为 C 结构编写 init 函数 [英] Writing init function for C struct
问题描述
这是我在头文件中的结构:
So this is my struct in a header file:
struct _Variable {
char *variableName;
char *arrayOfElements;
int32_t address;
};
typedef struct _Variable Variable;
这是我在 .c 文件中实现的 init 函数:
and here is my implementation of the init function in .c file:
void initVariable(Variable *variable, char *variableName, char *arrayOfElements,
int32_t address) {
int lengthOfVariableNameWithTerminatingChar = strlen(variableName) + 1;
variable->variableName = malloc(
sizeof(char) * lengthOfVariableNameWithTerminatingChar);
strncpy(variable->variableName, variableName,
lengthOfVariableNameWithTerminatingChar);
int lengthOfArrayOfElementsWithTerminatingChar = strlen(arrayOfElements)
+ 1;
variable->arrayOfElements = malloc(
sizeof(char) * lengthOfArrayOfElementsWithTerminatingChar);
strncpy(variable->arrayOfElements, arrayOfElements,
lengthOfArrayOfElementsWithTerminatingChar);
variable->address = address;
}
编译时没有错误,但运行测试文件时:
I get no errors when I compile but when I run my test file:
void test_initVariable() {
printf("\n---------------test_initVariable()-----------------\n");
// TODO:
Variable *variable1;
initVariable(variable1, "variable1", "1, 2, 3", 4); // <== Causes binary .exe file to not work
}
谁能告诉我如何修复我的实现?
Can anyone tell me how to fix my implementation?
推荐答案
Variable *variable1;
给你一个未初始化的指针.你不拥有它指向的内存,所以不能安全地写入它.
gives you an uninitialised pointer. You don't own the memory it points to so can't safely write to it.
您需要为 variable1
Variable variable1;
initVariable(&variable1, "variable1", "1, 2, 3", 4);
会起作用.
如果你希望 variable1
被动态分配,最简单的方法是让 initVariable
处理这个
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;
}
请注意,我还在这里简化了字符串的分配/填充.您的代码有效,但如果您使用的是与 posix 兼容的系统,strdup 非常有用实现相同结果的更简单方法.
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.
正如评论中所讨论的,如果 Variable
的字符串成员都是 字符串文字.在这种情况下,您可以将事情简化为
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;
}
这篇关于为 C 结构编写 init 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!