user321853
user321853

Reputation: 39

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

Upvotes: 1

Views: 3208

Answers (4)

jweyrich
jweyrich

Reputation: 32240

Besides the missing header, string.h, you can replace your malloc+strcpy by strdup.

units[0].name = strdup(buffer);

Upvotes: 4

Brian R. Bondy
Brian R. Bondy

Reputation: 347216

#include <string.h>

Upvotes: 2

Ken Bloom
Ken Bloom

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

WhirlWind
WhirlWind

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

Related Questions