我无法制作新阵列? [英] I am not able to make a new array?

查看:80
本文介绍了我无法制作新阵列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一个双倍长度的新arraylist,但是当我尝试制作一个长度为2 * size(array)的新数组时,它会给我一个错误,即

表达式必须有一个const值。

我该怎么办?



我尝试过:



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];

	}
	
}

推荐答案

您无法在堆栈上分配动态数组像这样:

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



您必须使用C ++ new 运算符。


You must use the C++ new operator.

int* pnew_arr = new int[leng];


你可以开始分配足够的金额(但这会浪费内存)



或,您可以使用指针(并将对象放在堆而不是堆栈上)。



有关详细信息,请参阅: C和C ++中的可变长度数组 - GeeksforGeeks [ ^ ]
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[^]


谢谢大家回答。

我确实找到了制作新阵列的解决方案,即



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



再次感谢你。
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.


这篇关于我无法制作新阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆