Pierre
Pierre

Reputation: 51

Issue with return pointer

I am trying to duplicate a copy of the array but the new copy needs to be in reverse order. My problem is my reverse function, I commented what the error is stating, what I don't understand is why it's stating that? If copy is a pointer variable? I'm still struggling with pointers, and I really just want some clarification on what I am doing wrong. I didn't make a reverse pointer variable yet, I was planning to do that once I figure out why I'm given this error.

Here's the function

int* reverse(int elements, int size)
{
    int* copy = new int [size];
    int k =0;
    for(int j=size-1; j >=0;j--)
    {
        copy[k] = size[j]; // Error-> Subscripted value is not an array,pointer or vector
        k++;
    }
    return copy;
}

Here's the entire code without the function,

#include <iostream>

int* allocation(int);
void output(int*, int);
int* reverse(int*, int);

int main()
{
    int size;
    std::cout << "Enter the size you want to allocate" << std::endl;
    std::cin >> size;
    int* array = allocation(size);
    std::cout << "Displays the elements of the array";
    output(array,size);
    return 0;
}

void output(int* array, int size)
{
    for(int k=0;k<size;k++)
    {
        std::cout << " " << array[k];
    }
}

int* allocation(int elements)
{
    int* ptr = new int[elements];
    std::cout << "Enter the elements for size of array." << std::endl;
    for(int i =0; i < elements; i++)
    {
        std:: cin >> ptr[i];
    }
    return ptr;
}

Upvotes: 0

Views: 63

Answers (1)

Rishi
Rishi

Reputation: 1395

The problem with your reverse function is that you are not passing pointer to source array which has to be copied in the reverse order. Instead, you have passed two ints.

The error

Error-> Subscripted value is not an array,pointer or vector

happens when you try to use size as an array by adding a subscript to it size[j] which is obvious because size is an int type and not a pointer, array or a vector

I have changed the signature of your function from

int* reverse(int elements, int size)

to

int* reverse(int *elements, int size)

I have modified your function to look this way

int* reverse(int *elements, int size)
{
    int* copy = new int [size];
    for(int j=size-1, k=0; j >=0; j--, k++)
    {
        // copy from elements and not size, elements is the array containing 
        // the values to be copied, size denotes the size of the array
        copy[k] = elements[j];  
    }
    return copy;
}

Side note:

  1. I have also put k in the scope of the for loop.
  2. You may want to use std::vector or std::array instead of using raw arrays
  3. I see that you have used the correct signature while defining the function int* reverse(int*, int);

Upvotes: 2

Related Questions