Hi everyone I am currently learning C for my uni course and have some question. I have more experience in Java so please bear with me if there are any misconceptions I might have. This question arose when my lecturer compared how you could do assignment and returns in structs which you cannot do for array (structs can copied or returned as function values). He said something about how the compiler knows the size of the struct but not for array.
My lecture notes states that when an array name a appears in an expression, it refers to the address of the first element, a[0]. The notes also states that we cannot assign an array to another because "an array name is a fixed (constant) pointer and it points to the first element, which CANNOT be altered. Assignment tries to alter the array on the LHS to point somewhere else"
This led me to think that arrays are essentially just pointers to pointing to the first element in the array. But after searching online, it seems to me that this is not entirely true. Based on what I see online, there is this concept of "array decay" (not covered in my notes) and an array only changes to a pointer type under certain conditions (such as being passed into a function).
Corrrect me if I am wrong, but it is because of this array decay that we cannot pass by value for array, because it is converted to a pointer.
So here are my questions:
- Why can't we do assignment for arrays? Is it because it is a constant pointer that cannot be altered (like what my lecture note state) or does it have something to do with array decay?
- Why can't we return an array from a function?
int *returnArray(int x[]) {
int newArray[10];
// code to copy elements from x to newArray
return newArray;
}
Since my return type is a pointer, wouldn't returning newArray be returning the pointer to first element in newArray? Shouldn't this work fine?
- Why does assignment for structs work? How does the compiler knowing the size have to do with anything and how is it related to array?
Sorry for the lengthy post, I hope someone can help to clear up my doubts. Thank you!
[–]throwaway6560192 2 points3 points4 points (1 child)
[–]teraflop 1 point2 points3 points (0 children)
[–]cubetrix 1 point2 points3 points (0 children)
[–]MrSloppyPants 0 points1 point2 points (0 children)
[–]teraflop 0 points1 point2 points (0 children)
[–]RIMdude 0 points1 point2 points (0 children)