为函数中的结构分配内存

时间:2015-03-10 17:57:35

标签: c memory struct

我需要为学校的项目制作一台adfgx机器(Code language from WWII)。但我遇到了一些问题。

有一个结构以及adfgx.h中定义的一些函数,如下所示:

typedef struct {
   char* alphabet;         
   char* symbols;          
   char* dictionary;       
   char* transposition;    
} adfgx;

在adfgx.c中,我们包含了头文件,我必须编写一个函数,为该结构分配一个带有预定义签名的内存:

/* Creates a new ADFGX machine */
adfgx* create_adfgx(const char* alphabet, const char* symbols, const char* dictionary, const char* transposition);

所以我应该在这里做的是为该函数中的struct分配内存。我不知道我应该怎么做,因为我现在没有字母,符号,字典和换位的大小,所以我现在怎样才能分配我需要分配的内存?

2 个答案:

答案 0 :(得分:1)

  

我现在不是字母,符号,字典和换位的大小

由于未传入大小,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;
}

现在您可以使用此功能填充struct

adfgx *res = malloc(sizeof(adfgx));
if (res == NULL) ...
res->alphabet = duplicate(alphabet);
...
return res;

答案 1 :(得分:1)

adfgx的大小不依赖于"字母,符号,字典和转置的大小" - 它是4个指针的大小。

关于为newAdfgx->alphabet和其他成员分配值,您可以使用strdup。释放free()的实例时,请务必strdup adfgx个字符串。

相关问题