简体   繁体   中英

Allocate memory for a struct in a function

I need to make an adfgx machine ( Code language from WWII ) for a project in school. But I am running into some problems.

There is a struct along with some functions defined in adfgx.h which looks like this:

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

In adfgx.c we include the header and I have to write a function that allocates memory for this struct with a predefined signature:

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

So what I am supposed to do here is allocate memory for the struct in that function. I don't get how I am supposed to do this, because I don't now the size of alphabet, symbols, dictionary and transposition, so how can I now hom much memory I need to allocate?

I don't now the size of alphabet, symbols, dictionary and transposition

Since the size is not passed in, the API must assume that const char* parameters represent C strings. This makes it possible to compute the desired size by calling strlen , and adding one to the result for the null terminator.

To avoid doing the same thing multiple times, I suggest defining your own function for string duplication:

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;
}

Now you can use this function to populate the struct :

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

The size of adfgx does not depend on "the size of alphabet, symbols, dictionary and transposition" - it's the size of 4 pointers.

As to assigning values to newAdfgx->alphabet and other members, you can use strdup . Just be sure to free() the strdup ed strings when you free the instance of adfgx .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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