Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 3 months ago.
The code goes as follows. while calling the function reverse_array, How do I define the first function argument as an array?
#include <stdio.h>
void swap(int* a, int* b);
void reverse_array(int a[], int n) {
int* b = a + n - 1;
while (b > a) {
swap(a, b);
a = a + 1;
b = b - 1;
}
}
void swap(int* ptra, int* ptrb) {
int t;
t = *ptra;
*ptra = *ptrb;
*ptrb = t;
}
main() {
int b[5] = { 1,2,3,4,5 };
reverse_array(b[5], 5);
int x;
for (x = 0; x < 5; x++) {
printf("%d", b[x]);
}
}
b[5]
is not the entire array but 6th element (the index start from 0) of the array, which doesn't exists.
You should pass b
instead. This will be converted to a pointer to the first element of the array.
When you write
`reverse_array(b[5], 5)`,
you are passing an int to the function as first parameter not an
array of int.
Compiler shows the error message “makes pointer from integer without cast” (reversing an array). How do i resolve this?
Do not pass an int
to where a pointer is expected. :)
Background:
In the context of a function definition something like int a[]
is the same as int * a
, so a
is a pointer to int
.
You caller passes b[5]
, which is the 6th element of the int
-array b
, so it's an int
(and BTW an out-of-bound access, as in C array are 0
-based so b
's element are addressed via indexes ranging from 0 to 4.
To "pass" the array just give b
.
reverse_array(b, 5);
The array b
would then be decayed to the address of its 1st element. This address is received within the function as value a
.