I have this program that makes and populates an array. Then it is sent to a function called reverse, which reverses the order in the array. The compiler keeps giving errors. I'm not quite sure why.
void reverse(int* array, int size) {
for (int i = 0; i < size/2; i++) {
int temp = array[i];
array[i] = array[size-i];
array[size-i] = temp;
} // end of for loop
} // end of reverse
int main( int argc, char** argv ) {
int array[8];
// get and print size of the array
int size = sizeof(array) / sizeof(array[0]);
printf("Size is %d\n", size);
// populate array
for (int i = 0; i < size; i++) {
array[i] = i;
} // end of for loop
// display array before reversing
for (int i = 0; i < size; i++) {
printf("%d ", array[i]);
} // end of for loop
// new line
printf("\n");
// reverse the array
reverse(&array, size);
// display the array again after reversing
for (int i = 0;i < size; i++) {
printf("%d ", array[i]);
} // end of for loop
} // end of main
I removed the & in front of the array variable when I send it to reverse. Though it gave me what I think is an address location. Below is the output. Why is that? There is no print statement in my code that intentionally prints any address.
You're getting that number because it's out-of-bound
Notice how the reversed of: 0 1 2 3 4 5 6 7 -> 7 6 5 4 3 2 1 0, but instead you're missing a 0 on the right hand side of the reversed and you have an extra value on the left hand side.
hint:
1 2 3 4 5 6 7 8 9 10
void reverse(int* array, int size) {
for (int i = 0; i < size/2; i++) {
int temp = array[i];
array[i] = array[size-i];
array[size-i] = temp;
} // end of for loop
} // end of reverse
void reverse(int* array, int size) {
int temp = 0;
for (int i = 0; i <= size/2; i++) {
temp = array[i];
array[i] = array[size-i-1];
array[size-i] = temp;
} // end of for loop
} // end of reverse
int main( int argc, char** argv ) {
int array[8] = {0};
// get and print size of the array
int size = sizeof(array) / sizeof(array[0]);
printf("Size is %d\n", size);
// populate array
for (int i = 0; i < size; i++) {
array[i] = i;
} // end of for loop
// display array before reversing
for (int i = 0; i < size; i++) {
printf("%d ", array[i]);
} // end of for loop
// new line
printf("\n");
// reverse the array
reverse(&array[0], size);
// display the array again after reversing
for (int i = 0;i < size; i++) {
printf("%d ", array[i]);