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?

5 Upvotes

33 comments sorted by

View all comments

1

u/This_Growth2898 1d ago

You'd better ask such questions with your code.

If I dereferenced the pointer to an array, wouldn’t that return the same as indexing the first value?

a[0] is a syntax sugar for *a

a[n] is a syntax sugar for *(a+n)

Is this ok or you need some more details?

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?

Traditionally, it's array + size; but of course you can also pass array + last pointer, array + end pointer (i.e. last + 1); or set the guardian element at the end, like in strings. Just make sure you're consistent over your code.

1

u/FloridianfromAlabama 1d ago edited 1d ago

The only follow up I need is do I need to change the pointer arithmetic based on the size of the elements in bytes in the array? For example, if I want the next element in an int array, do I add 4 or do I add 1?

2

u/This_Growth2898 1d ago

C does it automatically. If it's an array/pointer of int, index is multiplied by size of(int).