0

Completely new to pointers, so I apologize for the novice question. I am receiving a conversion error when trying to call my function. This function is supposed to return a pointer to an updated array that contains 1 at the end.

int* appendList(int x, int &arraySize, int *list)
{
    arraySize++;
    int *array2 = new int[arraySize];
    for(int i=0; i < arraySize-1; i++)
    {
        array2[i] = list[i-1];
    }
    array2[arraySize]=x;

    return array2;
}

My main function is as follows.

int main()
{
    int size=0;
    int *list;
    cout << "Please enter the size of your array: ";
    cin >> size;
    list = new int[size];
    cout << "\nPlease enter the numbers in your list seperated by spaces: ";
    for(int i=0; i < size; i++)
    {
        cin >> list[i];
    }
    cout << endl;
    cout << "The array you entered is listed below\n ";
    for(int i=0; i < size; i++)
    {
        cout << setw(3) << list[i];
    }

    list = appendList(1, size, list);
    for(int i=0; i < size; i++)
    {
        cout << setw(3) << list[i];
    }

    return 0;
}

The call to function appendList results in a conversion error for argument three, but I'm not sure why? The function parameters must stay the way they are.

Thank you for your help.

3
  • 1
    You use cout and setw without std::, so I guess you declared a using namespace std above. Then the list variable name may have collision with std::list<T>. Try use other name. Commented Feb 12, 2017 at 16:56
  • What other name could I use? Commented Feb 12, 2017 at 18:47
  • list1, my_list, ary, or some name different to c++ keyword or STL template. Or you may try not to use using namespace std; to expose all names from the std::. Commented Feb 13, 2017 at 5:58

1 Answer 1

2

A mistake that I found in your code.

 int* appendList(int x,int &arraySize,int *list)
        {
        arraySize++;
        int *array2=new int[arraySize];
        for(int i=0;i<arraySize-1;i++)
        {
            array2[i]=list[i-1];//this is incorrect because for i=0 it becomes list[-1] which is wrong
        }
        array2[arraySize]=x;

        return array2;
        }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I haven't even been able to debug it since I can't get the function to call correctly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.