在C ++中为变量分配大小 [英] Allocating size for a variable in c++

查看:63
本文介绍了在C ++中为变量分配大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我不知道所需的实际大小时,有人可以告诉我如何使用malloc初始化变量.目前,我正在使用:

Can somebody tell me how to initialize a variable using malloc, when I do not know the actual size required. For now I''m using :

int* a = (int*)malloc(100* sizeof(int));


我只是临时分配100.如何不使用大小进行初始化?


I''m only assigning 100 temporarily.How do I initialise without using the size?

推荐答案

您不能-malloc需要知道要多少个字节分配它-或不能确保将其装入可用的内存块中.
You can''t - malloc needs to know how many bytes you want it to allocate - or it couldn''t be sure to fit it into an available memory block.


您是说您不提前知道实际大小? malloc()和new都支持将变量用作输入.
You mean you don''t know the actual size ahead of time? Both malloc() and new support the use of variables as input.
//Example...
int *a = (int*) malloc(x*sizeof(int));
//Where x can be any positive integer




顺便说一句...如果您不知道大小,因为它会不断变化,那么您可以使用具有动态大小的东西,例如列表,而不是固定大小的数组.



edit:
by the way... if you don''t know the size because it''s going to keep changing, then you can use something with a dynamic size like a list instead of a fixed size array.


我永远不会理解的一件事是,为什么谁总是在学习C ++,却总是被诱惑(或引导)学习像C一样的语言.

C ++支持类和抽象类型,并具有一个标准库,其规范是语言的一部分,应与该语言一起研究.

看一下 std :: vector [
One of the thing I will never understand is why who is learning C++ is always tempted (or directed to) learn as it is C.

C++ support classes and abstract types and has a standard library whose specification is part of the language and that should be studied together with the language.

Give a look to std::vector[^].

All you need is a
std::vector<int> a;



然后,每次您有一个要插入的值时,只需调用



and then, every time you have a value to insert in it, just call

a.push_back(your_value);



然后,您可以使用a.size()知道大小,并像往常一样使用a[x]来访问值.



You can then know the size with a.size() and access the values as usual as a[x].


这篇关于在C ++中为变量分配大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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