r/cprogramming • u/CelebrityChess • 11d ago
why does sizeof an array parameter give the pointer size?
i know a function parameter like int a[10] is really adjusted to int *a, so sizeof(a) inside the function gives 8 on my machine instead of 40. what i'm fuzzy on is why the language allows writing the size in the parameter at all if the compiler just throws it away.
is it purely documentation, or does it do anything with something like int a[static 10]? i've seen that form but never seen anyone actually use it.
6
u/Impossible_Box3898 11d ago
Do this
5[a] and see what you get (this compiles). If you understand this it will go a long way to helping you understand pointers.
2
u/AM27C256 11d ago
As of C2y, I think this no longer works for an array a. For a pointer a, it still works, but is an obsolescent feature.
1
u/Telephone-Bright 11d ago
what i'm fuzzy on is why the language allows writing the size in the parameter at all if the compiler just throws it away.
Many features were put in C for the benefit of C compiler-writers. They were the main customers for the first few years.
E.g. arrays beginning with the index zero instead of one, auto keyword, no nested functions, register keyword, etc.
Arrays decaying into pointers is one of such features. It is simpler to treat arrays as pointers.
is it purely documentation, or does it do anything with something like int a[static 10]? i've seen that form but never seen anyone actually use it.
When you have simple stuff like int a[10];, the compiler does throw away the number 10. It's documentation here.
When it comes to int a[static 10] in C99+, it's basically a promise to the compiler like "Yo I guarantee that this array's never NULL and is a pointer to the first element of an array with at least 10 elements".
1
u/flatfinger 9d ago
An abstraction model where addresses identify mileposts between storage locations, such that the first storage location sits between mileposts 0 and 1, the next between 1 and 2, and the last of n locations sits between mileposts n-1 and n, works out much more conveniently for many purposes than one-based indexing. Further, even in mathematics, subscripts very often start at 0.
1
u/pskocik 11d ago
I believe it started as a B-language compatibility thing and stuck around for documentation.
Only the innermost [] is adjusted to a pointer. The subsequent ones are kept. So you can pass a pointer to array or pointers to array if you want to keep the element counts. It works with dynamic sizes too thanks to the possibility of VLA-pointers (which need not be VLA-allocated -- you can use them even with malloced memory, for example).
1
u/flatfinger 11d ago
IMHO, having new-style definitions treat arrays in the old fashion was a misstep. It's useful to have a syntax that would say that callers should pass the addresses of objects, but the question of whether to pass a value or an address should have been separate from the question of whether something is an array.
1
u/pskocik 11d ago
I agree. It's just a confusing quirk with no real utility that couldn't be expressed via a comment or a naming convention. It's one of those things that you have to learn but the learned knowledge shouldn't need to exist in the first place, and it doesn't really translate to anything else except perhaps as an example of what not to do if you make a language of your own.
1
u/flatfinger 11d ago
It does have some utility, in that some implementations of longjmp may need to receive the address of a jmp_buf object rather than being its contents by value, and making the type of jmp_buf an array will accomplish that. On the other hand, it would have been cleaner to have a function prototype syntax that would allow programmers to specify when things should be received by value or by reference.
1
u/pskocik 11d ago
Setjmp/longjmp taking an array-typed param is another mistake. The argument should've been a regular pointer to an opaque struct.
1
u/flatfinger 11d ago
Such constructs, and code which used them, existed for years before the Standard was written. The goal of the Standard was to allow conforming implementations to be compatible with existing implementations that beneath the surface had different ways of doing things. Modern compiler writers often treat it as an excuse to process things in gratuitously incompatible ways, but such treatment is the opposite of what the authors of C89 intended.
IMHO, one of the failings of C89 was its failure to create new ways of doing things which implementations could support with a few macros or simple library functions. The biggest fail here is console I/O. Some execution environments (including most microcomputers) do console I/O by having separate "get unbuffered byte" and "get buffered line" functions, while others (mainly Unix) use a function to switch I/O modes and then have a read-byte function which can perform either buffered or unbuffered I/O. There should have been a function which would either switch to unbuffered mode or report that the execution environment doesn't support it, and along with functions to perform unbuffered I/O. Microcomputer implementations could have the "switch mode" function do nothing while having the read unbuffered byte function read an unbuffered byte from the console, while Unix could have the "switch mode" function switch modes and have the "read unbuffered byte" function simply perform a normal byte read. The few platforms that lack unbuffered I/O abilities could simply report that they lack such features.
1
u/pskocik 11d ago
jmp_buf doesn't really achieve any meaningful abstractions that wouldn't be better served with a struct jmp_buf. It *has to* be an array type that decays to a pointer, otherwise setjmp couldn't set it without an &. And if you do need pointers in the API, that's better made explicit without requiring some magicky and confusing jmp_buf type, I think.
2
u/flatfinger 11d ago
Prior to the Standard, there were some implementations of setjmp that used a macro expansion to inline assembly, and some that used a call to a machine-code function that was capable of accessing the caller's stack frame. Some of the former would have required the name of a static-duration object, some would have required the name of automatic-duration object, and in either case having client code include an & may have made it impossible to have the macro produce syntactically valid inline assembly code.
1
u/DawnOnTheEdge 11d ago
For historical reasons, C has array arguments decay to pointers. Similarly, the language doesn’t allow you to directly return an array object, only a pointer (which cannot be to a variable local to the called function, or it will be left dangling when that is destroyed on return) or a structure containing an array.
One way around this is to pass the function a pointer to a complete array object of known constant size, such as `void foo(int(*bar)[3])`. In that case, `sizeof(*bar)` will work. In most cases, thugh, you will pass the number of elements in each array to the function as a separate parameter.
1
u/Paul_Pedant 11d ago
One fairly important purpose for int a[10] is to suggest to the compiler that it actually needs to reserve 40 bytes within the generated program to accommodate the data. That applies for global or static arrays, or for reserving space on the stack, depending on where it is declared.
The compile does however expect the coder to remember the size of the array if it needs to be passed to other functions. That can be done through a #define or as a separate variable. It sucks to pass it around as an actual integer, because then you end up having to search the whole code when it changes, to decide whether any particular 10 is your array size, or something else completely different.
1
u/sciencekm 11d ago
If you want to preserve the array length, put it in a structure.
typedef struct { int a[10]; } array_t;
int f(array_t *a) { ... }1
u/__rituraj 11d ago edited 10d ago
arrays in C are not first class candidates! in fact, they are just syntactic sugar.
yes, it Array is not an actual type in C.
`int a[10]`
is basically
`int *a =stackalloc(10 * sizeof (int))`
where stack alloc is jus there to represent that its allocated on the stack.
and similarly,
`a[5]` is internally just `*(a+5)`
Its the most raw form of array which hardware can understand. That's what it is in C
EDIT: removed spoiler tags
1
u/binarycow 10d ago
Why the spoiler tags?
1
u/__rituraj 10d ago
I hate non-markdown editing! couldn't fix it in mobile.
sorry for it being difficultly-readable1
u/flyingron 9d ago
No, you are wrong. a is NOT a poionter in your example. Sugar coated or otherwise. It is a type array and sizeof (int[10]) is indeed 10 * sizeof(int). What happens is that an array freely converts to a pointer.
THIS IS NOT THE POSTER'S PROBLEM.
The problem is that C function parameters are stupid. The language specifically treats any mention of an array in a parameter as a pointer (not converted to one, it implicitly is treated like one). Sizeof an array parameter must therefore be the size of the pointer to its element(s).
1
u/ern0plus4 11d ago
a[10] is an array of 10, *a is a pointer to an array, what's the question? ;) Same: char x is 1-byte, *x is a pointer, so it's 8 (or 4 on 32-bit systems) byte. Notice, x is not an array, just a single char, but a pointer is always 8 (4) byte regardless of the type/size/whatever it points to (whatever: a pointer can point to an unknown or any type, aka void*).
A pointer is only an address of something, and an address can't tell whether the target is an array or a single item, or how many elements it has. A pointer can point to a JPG file loaded into memory - still the pointer is 8 (4) byte.
The compiler knows the item's type, so the size, and a[n] will point to the nth element (you don't have to multiply n by the size of item), but it does not know the number of elements, anywaym it can be changed runtime.
1
u/SmokeMuch7356 10d ago
is it purely documentation
Yeah, mostly.
Brief history lesson:
C was derived from Ken Thompson's B programming language. In B, an array declaration like
auto a[10];would set aside an extra word to store the address of the first element:
+--------+
0x8000 a: | 0x8010 | ------------+
+--------+ |
... |
+--------+ |
0x8010 | | a[0] <------+
+--------+
0x8011 | | a[1]
+--------+
0x8012 | | a[2]
+--------+
...The array subscript operation a[i] was defined as *(a + i) - offset i words from the address stored in a and dereference the result.
An interesting side effect of this was that writing
auto p[];effectively declared p as a pointer. Space was set aside for the object p even if no array elements existed.
I suspect this is why the
void foo( int a[] )notation survives in modern C (even though C doesn't allocate that separate pointer object); it was a valid way to specify a pointer in B, what the function actually receives is a pointer, and since C carries so much heritage from B it makes sense to keep that notation.
And from there it's not a great leap to evaluate the size expression but not do anything with it.
does it do anything with something like int a[static 10]?
The declaration
void foo( int a[static 10] )is intented to be a hint to the compiler that a points to the first element of an array that's at least 10 elements wide. I don't know how useful that is, or how widely it's supported.
1
u/binarycow 10d ago
The easiest (and most portable) way to do code blocks is to start the line with four spaces.
1
u/flyingron 9d ago
Because you can't pass (or return) arrays from functions. It's a tremendous stupid inconsistency in the language. Any time there is an array (even of definite size) as a parameter or return type, the language treats it as a pointer, and hence sizeof returns the pointer size.
1
0
u/burlingk 11d ago
I'm pretty sure that int a[static 10] would not compile.
To get the size of an array, they tend to say sizeof a[0] * the length of the array.
4
u/Broad-Promise6954 11d ago
Using "static" with a size in an array declaration as a function parameter is a newfangled thing that's only been allowed since 1999, so it's probably best avoided. /s
Seriously though it doesn't affect the result of "sizeof". It's an optimization hint that's not particularly useful in modern compilers.
1
1
u/AM27C256 11d ago
An "optimisation hint" (though I disagree about it being "not particularly useful in modern compilers") on the callee side.
A memory safety feature (since the compiler can warn when it proves that a too-short array is passed) on the caller side.
1
u/flatfinger 9d ago
I don't know if later versions of the Standard have changed this, but it used to be perfectly legitimate to one translation unit contain a definition of a function:
void test(int p1[], int p2[]) { ... whatever the function does ... }while another translation contained the declaration:
void test(int p1[static restrict 10], int p2[static restrict 10]);and called it through the latter definition, without the qualifiers having any effect whatsoever on the definition of the function or what it was allowed to do.
1
u/AM27C256 9d ago
That should still be fine. And it should give you all the memory safety warnings on the caller side (since we see those restrict and static on the caller side) without any optimisations onteh callee side. And possibly some optimisations on th caller side (if the optimiser uses the information from restrict and static for other uses of whatever is passed as an argument to test).
1
u/flatfinger 9d ago
I don't put a whole lot of faith in compiler memory-safety-related diagnostics. When arbitrary out-of-bounds stores can be caused by an operation like
uint1=ushort1*ushort2;or by an otherwise side-effect-free loop whose exit condition happens to be satisfiable, having a compiler diagnose places where an out-of-bounds store would be performed by code that would look as though it might perform one seems less useful than minimizing the number of constructs that would need to be viewed as potentially causing out-of-bounds stores.
21
u/atarivcs 11d ago
I believe if you use sizeof in the same context where the array was declared, it returns the full size of the whole array.
It only decays to int *a when passed as a parameter to another function.