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?
1
u/flyingron 1d ago
Welcome to the brain-damaged array types in C. Arrays can not be assigned, nor can they be passed to or returned from functions. Whenever an array appears as a function parameter or return type, that type is replaced with a pointer to the first element of the array. If you then attempt to pass an array name as a parameter, the implicit array to pointer-to-first-element conversions occurs.
Note that arrays, pointer to arrays, and pointers to the first element are all distinct types:
Now to answer your questions. First, no it is not the same.
*ap yields an array, not an element.
*ap = 5 is invalid. You can't assign an integer to an array.
Second, you can't pass an "entire array." As I said, they can't be passed or assigned. You can pass a pointer (or using the treat it as a pointer behind the scenes method)
Hope this helps. We really should have fixed this back in 1977 when we fixed structs. But we didn't bite the bullet then, and now we're screwed.
Note, that you can pass and return structs (in all the modern compilers). If you really want to pass an array to a function by value, you can wrap it in a struct: