3 ms·
If I write: void example(int a[10]); Why can't the compiler tell a is an int array of size 10 instead of a pointer?
by acconsta 11y ago
If I write:
void example(int a[10]);
Why can't the compiler tell a is an int array of size 10 instead of a pointer?
- geocar 11y agosizeof(a) is sizeof(int*) in your example because of the C standard: That is to say this is a bug in the standard, and not a bug in any particular compiler.
- doppelganger27 11y agoThere is no strict difference between a pointer and an array (of any size) at run time in C. Arrays are just pointers to a section of memory, and it's up to the programmer to communicate how big that section is.
- 36erhefg 11y agoThere are whole separate chapters describing arrays and pointers in the C Standard. This is by definition a strict difference. You should read those chapters and please stop spreading this beginners misconception of C.
- deleted 11y ago[deleted]
- 36erhefg 11y agoIn any case, there are significant differences at runtime as well. Look at the link I posted at your other comment.
- 36erhefg 11y agoBecause a is a pointer and not an array. That is by design. When you pass an array to this function you are not copying the entire array, C is pass by value, therefore you must pass a pointer. In fact a behaving like an array would be lying to the programmer since you didn't make a copy of the array.
- acconsta 11y agoYou can pass structs by value. Why not arrays?
- 36erhefg 11y agoYour answer is merely a simple online search away.
- acconsta 11y agoWhat's weird is five hours after asking that question, no one has provided a reasonable explanation of why C requires arrays to become pointers on function boundaries. My "online search" found Walter Bright, who knows a thing or two about C compilers, wondering the same thing: https://news.ycombinator.com/item?id=7572011 https://news.ycombinator.com/item?id=7572011
- 36erhefg 11y agoImprove your searching capabilities. https://programmers.stackexchange.com/questions/245602/why-cant-arrays-be-passed-as-function-arguments-in-c https://programmers.stackexchange.com/questions/245602/why-c... ( https://stackoverflow.com/questions/7454990/why-cant-we-pass-arrays-to-function-by-value https://stackoverflow.com/questions/7454990/why-cant-we-pass... ) And partially this thread. As for Walter; Stop using C like you want it to be used, and instead how it is meant to be used. The article takes a strawman position. Anyone who takes their time and learns C, knows that arrays decay.
- 11y ago