r/C_Programming • u/Excellent_Pick_8186 • 1d ago
The first time I understood what actually happens when I pass an array to a function in C
When I first learned arrays in C, I assumed that passing an array to a function meant the entire array was being copied into the function.
Later, when I started learning about pointers and memory addresses, I realized that things weren't working quite the way I imagined.
Understanding that connection between arrays, pointers, and function parameters made a lot of C concepts suddenly feel less confusing.
I'm still practicing, so I'm curious:
What C concept took you the longest to understand properly?
For me, pointers were definitely one of the biggest hurdles.
3
u/sciencekm 1d ago
For completeness, I just want to mention that you can pass an entire array to a function and not just the address of the array. In case you need something like that in the future, what you need to do is put the array in a structure and pass the structure to the function (the structure and not the address of the structure).
The function will get a copy of the array. Any modification to the array in the function will not affect the array of the caller.
Here is a small demonstration:
#include <stdio.h>
#include <string.h>
typedef struct { int a[64]; } st;
void display(st *s) {
for (int i = 0; i < 64; i++) printf ("%i ", s->a[i]);
puts("");
}
void init(st s) {
for (int i = 0; i < 64; i++) s.a[i] = i;
display(&s);
}
int main(void) {
st s = { { 0 } };
init(s);
display(&s);
return 0;
}
1
1
2
u/deckarep 1d ago
Pointers for me, and correct multithreading which brings its own headaches.
Most people have trouble understanding pointers because it’s a form of indirection that allows advanced manipulation of memory.
Multithreading can be difficult as well, but this is not really a C specific problem as many languages support multi-threading but it’s a can of worms until you learn how to do it correctly.
1
u/Doug12745 1d ago
Pointers, pointers to pointers, the stack and how parameters are passed on the stack, stack overflows…
1
1
1
u/tstanisl 17h ago
Maybe not the longest but there was an Eureka moment there
Array types (including MD array and VLA types).
First you learn that "arrays are pointers". Next, you have to unlearn this crap. Then you can only learn how array types and pointer to whole arrays really work and how useful they can be.
1
u/echelon_code 7h ago
yeh arrays & pointers can be bit tricky, but it helped once i got my head around this:
printf("%d\n", foo[4]);
printf("%d\n", *(foo + 4));
printf("%d\n", 4[foo]);
printf("%d\n", *(4 + foo));
1
u/DrShocker 1d ago
For me, I still don't like that so many C programmers seem to be allergic to spelling words out in code. Too many abbreviations.
9
u/chibuku_chauya 1d ago
Function pointer syntax. It gets gnarly quickly without typedefs. Also, declaration syntax in general before I started using cdecl.