aspire29 aspire29 - 3 months ago 9
C++ Question

Invalid conversion error while passing a dynamic array to a function in C++

I am new to C++. I am trying to write a program which can resize an array while running the program. Every time I try to pass the array, it says "Invalid coversion from int to int* [-fpermissive] ". I have tried writing it in another way as well but this error still comes up.
Heres the code I wrote:-

#include <iostream>

using namespace std;

void resizeArray ( int p_int, int startingSize, int new_size );
void printArray ( int p_int, int new_size );

int main ()
{
int startingSize = 3; // I set this to three in order to avoid confusion
int *p_int = new int [ startingSize ];

for ( int i = 0; i < startingSize; i++ )
{
cout << "Value of Element [ " << i << "] : " ;
cin >> p_int [ i ];
}

int userInput = 3;// I set this to three in order to avoid confusion
cout << "How many more would you like to add? :" ;
cout << userInput << endl;

int new_size = startingSize + userInput;

resizeArray ( p_int, startingSize, new_size );

for ( int i = startingSize; i < new_size; i++ )
{
cout << "Value of Element [ " << i << " ] : ";
cin >> p_int [ i ];
}

printArray ( p_int, new_size );

delete [] p_int;

return 0;
}

void resizeArray ( int p_int, int startingSize, int new_size )
{
int *temp = new int [ new_size ];
for ( int i = 0; i < startingSize; i++ )
temp [ i ] = p_int [ i ];
delete [] p_int;

p_int = temp;

}

void printArray ( int p_int, int new_size )
{
cout << "~~ Complete Array ~~ " <<endl;
for ( int i = 0; i < new_size; i++ )
{
cout << "Element [ " << i << " ] = " << p_int << endl;
}


}


Thanks!

Answer

int will never magically interpreted as int* or int*&. Use proper types for the arguments like this:

void resizeArray ( int*& p_int, int startingSize, int new_size );
void printArray ( const int* p_int, int new_size );

Don't forget to update both of declaretions and definitions.

I used int*& p_int for resizeArray() because p_int should be a pointer and modifying caller's local variable seems intended.

I used const int* p_int for printArray() because passing (a pointer to the first element of) array should be intended and modifying the passed array doesn't seem intended.

Also I guess you want to use p_int[i] instead of p_int in the printing statement in printArray().

Comments