What causes the crash is undefined behaviour. When passing an array to a function, that array decayes into a pointer (memory address) of the first element of that array. Fine, you can still use the []
operator on a pointer, but it's up to you to make sure that a_ptr[123]
is still valid, and accessible memory.
If it isn't anything can happen. That's why it's called undefined behaviour.
If, say, the memory address of reverse[0]
is 0x04
, and sizeof(int)
is 4, then reverse[-1] = 123
is the same as writing: *((int *) 0) = 123;
. That is textbook undefined behaviour (dereferencing a NULL pointer!).
more on this matter
You are accessing memory you don't own, memory that is out of bounds: your arrays are defined as 3 long, but you're looping using the size
macro (should be upper-case, BTW), which is 50. That is not allowed, hence the crash. Change the revarr
function to take a third argument, specifying the length of the array to reverse, and make sure both arrays you pass are big enough to accommodate the data:
#include <stdio.h>
#include <stdlib.h>
void rev_array(int *to, int *from, size_t max)
{//arrays decay into pointers
int i,j;
for (i=max-1, j=0;j<max;--i,++j)
to[j] = from[i];
}
int main ( void )
{
int i,
reverse[3],
num[] = {1,2,3};
rev_array(reverse, num, 3);
for(i=0;i<3;++i)
printf("%d -> %d\n", num[i], reverse[i]);
return EXIT_SUCCESS;
}
As you can see here, it works perfectly.
Instead of hard-coding the 3, you can get the size of an array using sizeof
, of course (note: sizeof
works on arrays, not on pointers!):
rev_array(
reverse,
num,
sizeof num/sizeof *num
//or sizeof(num)/sizeof(num[0])
);