C ++动态分配数组,这是错的吗? [英] C++ dynamically allocating arrays , is this wrong?
问题描述
你好
我想接受用户输入并使其达到动态数组的大小,
我做了这个就像你一样可以在下面的代码中看到。
问题是:我只是想知道这是否正确的方法呢?
i已经测试过,甚至做过内存泄漏测试,但一切都很好。
谢谢: )
我的尝试:
int userinput = 0;
cout<< 输入数组大小:<< std :: endl:
cin>> userinput;
//我有一个名为Runner的班级。
Runner * arr = new Runner [userinput ];
delete [] arr;
Hello
I want to take user input and make it the size of a dynamic array,
and i did this as you can see in code below.
the question is: I just wondring if this is right way to do it ?
i have tested and even did a memory leak test but everything was just fine.
Thank you :)
What I have tried:
int userinput = 0;
cout << "Enter array size: " << std::endl:
cin >> userinput;
//I have class named Runner.
Runner * arr = new Runner[userinput];
delete [] arr;
推荐答案
是的,对我来说很好看。
使用这种技术你唯一需要注意的事项 - 如果Runner对象有一个需要参数的构造函数,那么就无法做到这一点。那时你需要使用std :: vector或指针数组来代替Runner,然后分别初始化(并销毁)每个元素。
Yep, looks good to me.
The only thing you need to be aware of using this technique - if the Runner objects have a constructor that requires a parameter, this cannot be done. That's when you either need to use a std::vector or an array of pointers to type Runner instead, and then initialise (and destroy) each element separately.
这篇关于C ++动态分配数组,这是错的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!