2

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.

harald
6,1561 gold badge26 silver badges43 bronze badges
asked Jun 11, 2013 at 7:22
1
  • By the way, your malloc() argument doesn't make any sense. You mean (strlen(a) + 1) * sizeof (char), but since sizeof (char) is always 1, this should just be written as strlen(a) + 1. Commented Jun 11, 2013 at 7:48

3 Answers 3

8

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.

answered Jun 11, 2013 at 7:27
Sign up to request clarification or add additional context in comments.

Comments

5

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

typedef struct{
 char * foo; 
} TYPE;
answered Jun 11, 2013 at 7:24

1 Comment

Why does it not work as an array? To my (limited) understanding the pointer notation is just another way of writing an array
4

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.

answered Jun 11, 2013 at 7:34

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.