. Advertisement .
..3..
. Advertisement .
..4..
I’m trying to run a new project. I do a couple of things like this:
#include <stdio.h>
#define N 30
typedef struct{
char name[N];
char surname[N];
int age;
} data;
int main() {
data s1;
s1.name="Paolo";
s1.surname = "Rossi";
s1.age = 19;
getchar();
return 0;
}
s1.name="Paolo"
s1.surname="Rossi"
data s1 = {"Paolo", "Rossi", 19};
But in my program, I am getting the warning:
"error: assignment to expression with array type error"
Can someone explain why the “error: assignment to expression with array type” issue happened? Where have I gone wrong? Thank you!
The cause: It shows the error “Not Assignable” because assigning a value to a string directly in C is not feasible.
Solution:
You should use
strcpy()
function to modify the valueDo it in the following way:
data
is a block of memory that can hold 60 characters plus 4 for the int. (See note).This allocates memory to the stack.
Assignments are not just copies of numbers; sometimes they can be pointers.
This is a failure
Because
s1.name
is at the beginning of a 64-byte-long struct, and"Paulo"
is 6 bytes (6 because of trailing 0 in C string strings), the compiler can assign a pointer for a string to a string.To copy “Paulo into struct at point
name
and “Rossi into struct at Pointsurname
.What do you end up with?
strcpy
does the exact same thing, but it knows about\0
termination and does not require the length to be hardcoded.Alternativly, you can also define a structure that points at char arrays any length.
This will result in
Now, you can fill the struct using pointers.
This is what it looks like
Pointers are 4 and 10.
Please note that the pointers and ints can have different sizes. For example, size 4 is 32bit.