Search
 
SCRIPT & CODE EXAMPLE
 

CPP

reverse an array using pointers in c++

#include <iostream>

using namespace std;


int* reverse(int* list, int size)
{
  for (int i = 0, j = size - 1; i < size; i++, j--)
  {
    // Swap list[i] with list[j]
    int temp = list[j];
    list[j] = list[i];
    list[i] = temp;
  }

  return list;
}

void printArray(const int* list, int size)
{
  for (int i = 0; i < size; i++)
    cout << list[i] << " ";
}

int main(){
    int list[6] = { 1,2,3,4,5,6 };
    int *ptr = reverse(list, 6);
    printArray(list,6);
}
Comment

c++ array rev pointer

// CPP program to reverse array
// using pointers
#include <iostream>
using namespace std;
  
// Function to swap two memory contents
void swap(int* a, int* b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}
  
// Function to reverse the array through pointers
void reverse(int array[], int array_size)
{
  
    // pointer1 pointing at the beginning of the array
    int *pointer1 = array,
  
        // pointer2 pointing at end of the array
        *pointer2 = array + array_size - 1;
    while (pointer1 < pointer2) {
        swap(pointer1, pointer2);
        pointer1++;
        pointer2--;
    }
}
  
// Function to print the array
void print(int* array, int array_size)
{
  
    // Length pointing at end of the array
    int *length = array + array_size,
  
        // Position pointing to the beginning of the array
        *position = array;
    cout << "Array = ";
    for (position = array; position < length; position++)
        cout << *position << " ";
}
  
// Driver function
int main()
{
  
    // Array to hold the values
    int array[] = { 2, 4, -6, 5, 8, -1 };
  
    cout << "Original ";
    print(array, 6);
  
    cout << "Reverse ";
    reverse(array, 6);
    print(array, 6);
    return 0;
}
Comment

PREVIOUS NEXT
Code Example
Cpp :: cpp random in range 
Cpp :: c++ randomization 
Cpp :: C compile SDL program using mingw 
Cpp :: print queue c++ 
Cpp :: capacity() in c++ 
Cpp :: landscape overleaf 
Cpp :: taking input from user in array in c++ 
Cpp :: __lg(x) in c++ 
Cpp :: qlabel set text color 
Cpp :: how to hide ui elements unity 
Cpp :: qstring to char* 
Cpp :: how to free the vector c++ 
Cpp :: convert string to stream c++ 
Cpp :: declare dynamic array c++ 
Cpp :: string count occurrences c++ 
Cpp :: cmath sqrt 
Cpp :: array 2d dynamic allocation c++ 
Cpp :: opencv c++ hello world 
Cpp :: C++ convert integer to digits, as vector 
Cpp :: copy 2 dimensional array c++ 
Cpp :: maximum int c++ 
Cpp :: sort vector in descending order 
Cpp :: scan line in c++ 
Cpp :: adding element in vector c++ 
Cpp :: ue4 c++ enumaeration 
Cpp :: print each number of digit c++ 
Cpp :: c++ enum 
Cpp :: all possible permutations of characters in c++ 
Cpp :: c++ template function 
Cpp :: create a 2d vector in c++ 
ADD CONTENT
Topic
Content
Source link
Name
2+1 =