简体   繁体   中英

Allocating memory for a char pointer that is part of a struct

im trying to read in a word from a user, then dynamically allocate memory for the word and store it in a struct array that contains a char *. i keep getting a implicit declaration of function âstrlenâ so i know im going wrong somewhere.

struct unit
{
  char class_code[4];
  char *name;
};

char buffer[101];
struct unit units[1000];

scanf("%s", buffer);

units[0].name = (char *) malloc(strlen(buffer)+1);
strcpy(units[0].name, buffer);

Implicit declaration of function 'strlen' means that you forgot to #include the header that declares it, in this case <string.h>

That's the only error I see in your code.

除了缺少的标头string.h ,您还可以用strdup替换malloc + strcpy。

units[0].name = strdup(buffer);
#include <string.h>

Make sure you are doing:

#include <string.h>

to include the strlen() function declaration.

Also, you should really be using strnlen() and strncpy() to prevent bugs.

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