C array declaration and assignment?
I've asked a similar question on structs here but I'm trying to figure out how C handles things like assigning variables and why it isn't allowed to assign them to eachother if they are functionally the same.
Lets say I have two arrays:
int x[10];
int y[10];
Why won't x = y compile? If they are both the same "signature" like that, then shouldn't you be able to assign them back and forth?
Can I declare these in a way that would allow me to do that in C? It makes sense to me that you would be able to, but maybe there is a way that this can be done? Typedefs for structs seemed to be the solution, would it be the same for array declaration and assignment?
I appreciate your guys help, I'm new to Stackoverflow but it has been a really good resource for me so far!
Solution 1:
Simply put, arrays are not assignable. They are a "non-modifiable lvalue". This of course begs the question: why? Please refer to this question for more information:
Why does C++ support memberwise assignment of arrays within structs, but not generally?
Arrays are not pointers. x
here does refer to an array, though in many circumstances this "decays" (is implicitly converted) to a pointer to its first element. Likewise, y
too is the name of an array, not a pointer.
You can do array assignment within structs:
struct data {
int arr[10];
};
struct data x = {/* blah */};
struct data y;
y = x;
But you can't do it directly with arrays. Use memcpy
.
Solution 2:
int x [sz];
int *y = x;
This compiles and y
will be the same as x
.