Click here to Skip to main content
15,892,927 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to make a new arraylist of double length than the existing one, but when i try to make a new array of length 2*size(array), it is giving me an error which is
"expression must have a const value".
What should i do?

What I have tried:

int arr[5];
int index;
int n = std::size(arr);

bool insert(int element, int index) {
	if (index<0 && index>n) {
		printf("Enter a valid index:\n");
		return false;
	}
	int const leng = 2*n;

	if (index==n) {
		int new_arr[leng];

	}
	
}
Posted
Updated 12-Sep-18 4:41am
Comments
KarstenK 12-Sep-18 4:30am    
you code is showing that you really need to learn the language. Answering your question will not move you out of the trouble. ;-)

You cannot allocate dynamic arrays on the stack like so:
C++
int new_arr[leng];

You must use the C++ new operator.
int* pnew_arr = new int[leng];
 
Share this answer
 
You could allocate a significantly adequate amount to begin with (but this wastes memory)

Or, you could use pointers (and place the object on the heap instead of the stack).

For further info, please see: Variable Length Arrays in C and C++ - GeeksforGeeks[^]
 
Share this answer
 
Thank you all for answering.
I did found a solution for making a new array i.e.,

int *new_array=new int[2*n];

thank you again.
 
Share this answer
 
Comments
Richard Deeming 13-Sep-18 15:19pm    
Which is exactly the same code as solution 2!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900