我需要为学校的项目制作一台 adfgx 机器 ( Code language from WWII )。但是我遇到了一些问题。
adfgx.h 中定义了一个结构和一些函数,如下所示:
typedef struct {
char* alphabet;
char* symbols;
char* dictionary;
char* transposition;
} adfgx;
在 adfgx.c 中,我们包含了 header ,我必须编写一个函数,使用预定义签名为此结构分配内存:
/* Creates a new ADFGX machine */
adfgx* create_adfgx(const char* alphabet, const char* symbols, const char* dictionary, const char* transposition);
所以我在这里应该做的是为该函数中的结构分配内存。我不明白我应该怎么做,因为我现在不知道字母表、符号、字典和换位的大小,所以我现在如何分配需要分配的内存?
最佳答案
I don't now the size of alphabet, symbols, dictionary and transposition
由于未传入大小,API 必须假定 const char*
参数表示 C 字符串。这使得可以通过调用 strlen
并将结果加一作为空终止符来计算所需的大小。
为避免多次执行相同的操作,我建议定义您自己的字符串复制函数:
static char *duplicate(const char *s) {
if (s == NULL) return NULL;
size_t len = strlen(s)+1;
... // Call malloc, check results, make a copy
return res;
}
现在您可以使用此函数填充结构
:
adfgx *res = malloc(sizeof(adfgx));
if (res == NULL) ...
res->alphabet = duplicate(alphabet);
...
return res;
关于c - 为函数中的结构分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28970800/