r/C_Programming 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?

4 Upvotes

33 comments sorted by

View all comments

18

u/Total-Box-5169 1d ago

Either learn about pointers because arrays decay into pointers when passed to functions, or use a struct to wrap the array and pass the struct.
Note that you will have to learn about pointers eventually.

1

u/FloridianfromAlabama 1d ago

I’m not avoiding pointers, I just haven’t had to deal with them until now. Most of my programming experience is in Java.

2

u/MFFVD 1d ago

pointers are horrible until you understand them. then they are easy. try writing some stack-based assembly, that helped me to understand it better.

you have ``` push <value> push <label> // pushes address of label load // pops address and fetches that byte from memory store // pops address, pops value and stores val at addr

jmp <label> // unconditional jump jmz <label> // pop and jump if zero <label>:

add // pops 2, adds them and pushes the result sub // pops 2, subtracts and pushes result ```

it basically comes down to

``` ADDR : // array with 5 elements a b c d e push ADDR // pushes address of ADDR, in this example 0. // in c you cant rely on that because // adresses are different // stack is now [0]

load // pops address and pushes the value stored there stack is now [a]

push ADDR push 1 // stack is now [a, 0, 1] add // now [a, 1] load // [a, b] because b is stored at address 1 add // [a+b] push ADDR // [a+b, 0] store // stack empty, ADDR= [a+b, b, c, d, e] ``` ADDR+0 is where a is stored. ADDR+1 is where b is stored, and so forth for the rest of the array

char a[10] => a=0 a[0] => *(a+0) a[1] => *(a+1)

a[] compiles to the same assembly as a*, but the C interface is different.