Reputation: 39
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);
Upvotes: 1
Views: 3208
Reputation: 32240
Besides the missing header, string.h
, you can replace your malloc+strcpy by strdup.
units[0].name = strdup(buffer);
Upvotes: 4
Reputation: 58770
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.
Upvotes: 7
Reputation: 14112
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.
Upvotes: 1