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 fo开发者_运维问答r 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.
Besides the missing header, string.h
, you can replace your malloc+strcpy by strdup.
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.
精彩评论