views:

248

answers:

4

hi, 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);
+1  A: 

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.

WhirlWind
There's no bug here. He's allocating enough memory for the string, based on knowing the contents of the string. That's perfectly safe use of `strcpy`. The use of `strlen` is also fine, so long as `scanf` doesn't overflow `buffer`. He might want to add a field length on the `%s` to ensure that.
Ken Bloom
In this case, `"%100s"` as the `scanf` format string.
caf
+7  A: 

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.

Ken Bloom
thank you, i knew it would something like that but couldnt think of what it was. im still new to this so i make heaps of stupid mistakes
+2  A: 
#include <string.h>
Brian R. Bondy
+3  A: 

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

units[0].name = strdup(buffer);
jweyrich
jweyrich: Does strdup() allocate memory to char*? So u can do strcpy(units[0].name, "123") and then free(units[0].name) when done? Is this ANSI C?
Sunscreen
@Sunscreen: yes
Ken Bloom
Cool, I ll use it when I can :)
Sunscreen