如果可能,请告诉我如何将元素添加到非固定大小的数组中!
这是我的代码:
#include <iostream>
#include "../Headers/print.h"
#include <string>
using namespace std;
int cells[] = {0};我想给cells添加更多的元素,但是我找不到答案,我试过的所有东西都不起作用……
谢谢!
发布于 2020-01-25 15:44:31
如何在C++中向非固定大小的数组添加元素?
首先,数组的大小是固定的。当你像这样初始化一个数组时,你可以跳过指定大小,
int cells[] = {0};数组的大小由编译器自动推断。
如果您需要动态大小的数组,请使用向量。有关示例,请参阅下面的代码。
#include <iostream>
#include <vector>
int main(){
int cells1[] = {0}, cells2[] = {0,1,2,3,4,5};
std::cout<<"Size of cells1 array: "<<sizeof(cells1)/sizeof(cells1[0])<<std::endl; // 1
std::cout<<"Size of cells2 array: "<<sizeof(cells2)/sizeof(cells2[0])<<std::endl; // 6
std::vector<int> cells3{0}; // Vector - a dynamic array
std::cout<<"Size of cells3 vector: "<<cells3.size()<<std::endl; // 1
cells3.push_back(1); // Append an element to the end of vector
std::cout<<"Size of cells3 vector: "<<cells3.size()<<std::endl; // 2
return 0;
}输出
Size of cells1 array: 1
Size of cells2 array: 6
Size of cells3 vector: 1
Size of cells3 vector: 2发布于 2020-01-25 16:06:17
你可以得到对第一个元素的引用&单元格加上这个数目的元素乘以它们的大小+1* sizeof(int),这样你就得到了数组后第一个字节的地址。然后,您可以使用以下命令在此地址分配内存:https://stackoverflow.com/a/19103230/11685627 allocate sizeof(int)*no of element。那么您应该能够使用您的数组,因为它在大小上进行了扩展。记住在数组超出块作用域后“释放”内存。https://docs.microsoft.com/en-gb/windows/win32/api/memoryapi/nf-memoryapi-virtualalloc?redirectedfrom=MSDN https://docs.microsoft.com/en-gb/windows/win32/api/memoryapi/nf-memoryapi-virtualfree Ofc这是一种非常困难的方法。
https://stackoverflow.com/questions/59907257
复制相似问题