Question

So i'm learning structures and am trying inputting a string with dynamic memory allocation.

Here is what I have so far:

  typedef struct{
    char foo[81]; 
  } TYPE;


 void function(TYPE get[]){
   char a[81];
   scanf("%s", a);

   get->foo = malloc(strlen(a)+1*sizeof(char)); //this line produces an error that it is not assignable

   strcpy(get->foo,a);

   return; 

 }

I'm not sure what is wrong with that statement, any help would be well appreciated.

Was it helpful?

Solution

foo is an array object and not a pointer so you can not use the operation

get->foo = (char*)calloc(strlen(a)+1,sizeof(char));

you are trying to assign a (void *) to type char[81], which is totally incompatible. Lvalue should be pointer in this case.

OTHER TIPS

You have to declare you foo to be a char pointer.

typedef struct{
    char * foo; 
} TYPE;

You are trying to allocate memory for foo and assign it the address of the allocated memory. That won't work. foo is an array, and has already memory allocated to it (81 char elements.) And because it's an array, you can't assign an address to it.

What you want is to copy the a string to foo:

scanf("%s", a);
strcpy(get->foo, a);

However, you can do better by actually limiting the scan and copy operations to 81 characters, so that you won't write past the end of foo nor a:

fgets(a, 81, stdin);
strncpy(get->foo, a, 81);

Consulting the docs for fgets() and strncpy() is a good idea (there you can find out why you can specify 81 instead of 80 in the call to fgets().) You should always be careful not to write past the end of an array.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top