-1

I am learning C++ by myself through Udemy courses, and now thanks to some good advice I'm using a book "C++ Primer".

I will show you one of my codes. Please give me any advice on my route to programming, and why it does not work. It does not show the values in reversed manner using pointers.

#include <iostream>
using namespace std;
using std::cin;
using std::cout;
using std::endl;

 
void reverse_array (int *arr, int size)
{
    int *start = arr;  
    int *end = arr + size -1;

    while (start < end)
    {
        int temp = *start;
        *start = *end;
        *end = temp;
        start ++;
        end --;
    }
}

int main ()
{
    int arr [] {1,2,3,4,5,6,7};
    int size = sizeof(arr)/ sizeof(arr[0]);

    reverse_array (arr,size);

    cout << reverse_array << endl;
}
12
  • 3
    cout << reverse_array << endl; Printing an array in C++? Also, you should print the array, not the function. Commented Dec 29, 2023 at 18:00
  • Also, you have an extraneous int main () { at the start of the program. Commented Dec 29, 2023 at 18:01
  • 1
    Change int size = sizeof(arr)/ sizeof(arr[0]); to auto size{ std::size(arr) }; Commented Dec 29, 2023 at 18:11
  • void reverse_array (int *arr, int size) returns nothing, so even once you get the call sorted out, still can't print the result. Commented Dec 29, 2023 at 18:11
  • 1
    @Alex87 The code basically works. You're just not printing the array correctly. godbolt.org/z/efYYdb1oj Commented Dec 29, 2023 at 19:07

1 Answer 1

1

This is my answers for your code problems. In your code, when you use [cout <<"reverse Array" << endl], you are trying to print the address of reverse_array function instead of printing the function has been reversed. To print index in an array, you have to use a "for-loop" and print every single index.

When calling the reverse_array function, you pass only the arr and size arguments without the & sign to indicate the address of the array. Therefore, in the reverse_array function, the arr parameter is copied and changing the value of arr does not affect the array in the main function. To invert the array in the desired way, you need to pass the address of the array using &arr[0] or arr.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.