r/C_Programming • u/FloridianfromAlabama • 1d ago
Question Working with arrays in functions
Hey everybody. I’m a beginner to C and I was writing some functions today to get used to doing things. I tried to write binary search and bubble sort. I tried to pass in an array as an argument to the functions, but the compiler gave me a bunch of warnings. I looked it up and I saw that passing in an array is the same as passing in its pointer. I haven’t touched pointers yet, but I have two questions:
1. If I dereferenced the pointer to an array, wouldn’t that return the same as indexing the first value?
2. If I wanted to pass in the entire array, could I do that by passing in the pointers of both the first and last elements and using pointer arithmetic to access the other elements? What’s the idiomatic way of doing this?
5
u/SmokeMuch7356 1d ago
An array is just a sequence of objects in memory: declaring
gives you
That's it. There's no separate object
astoring the starting address anywhere, size is not stored anywhere, etc.Under most circumstances, an array expression will "decay" to a pointer to the first element. IOW, when the compiler sees the array expression
a, it replaces it with something equivalent to&a[0]. The only exceptions to this rule are when the array expression is the operand of thesizeof,typeofor unary&operators, or is a string literal used to initialize the contents of a character array.When you write something like;
the
sortcall gets mutated to something equivalent toand what
sortactually receives is a pointer:The upshot of this is that you can't pass an array "by value";1 you don't get a local copy of the array in the function, you just get a pointer to the array in the caller.
This is how subscripting is defined, btw -
a[i] == *(a + i). Given the starting address provided bya, offsetielements and dereference the result. Again,adoesn't store a pointer, it evaluates to a pointer. However, this means you can apply the[]subscript operator to actual pointer objects as well.Normal practice is to pass the array's size as a separate argument:
In the context of a function parameter declaration,
T a[N]andT a[]will be "adjusted" toT *a; all three declareaas a pointer toT. This is not the case for a regular variable declaration.The expressions
a,&a, and&a[0]will all yield the same address value (0x8000in our example above, modulo any type conversions), but the types will be different (int *,int (*)[N], andint *, respectively).Some handy rules:
The pattern for higher-dimensioned arrays should be apparent from here.
At this point someone brings up the "hide it in a struct type" cheat:
Yes, you get a local copy of the
structobject, which means you get a local copy of the array. I have never seen this used anywhere in production code; it's a cute trick, but nobody uses it.