Closed. This question needs details or clarity。它当前不接受答案。                                                                                                                                                                                                                                                                                                                        想改善这个问题吗?添加详细信息并通过editing this post阐明问题。                                                5年前关闭。                                                                                                                    有什么方法可以计算动态分配的数组中的元素数?使用静态分配的数组没有用(它给我堆栈溢出错误),因为我需要分配一个缓冲区大小来存储100,000个双精度值的数据(100000 * 8 = 800000字节)。无论如何,我无法通过静态数组来做到这一点,但实际上我不想在Stack上分配这么大的缓冲区,而Heap将是首选。所以这就是我所做的。静态分配的数组,这里的大小是我实际需要的(在这种情况下肯定会失败),但是后来我尝试使用较小的大小,它可以为我工作并打印出元素数量but this is not what i want i need something which can count how many elements are actually entered by for loop not just return whole size (800010*8),即像我们为,然后是char buffer[1000]。srand (time(0));double arr[800010]; for(int i = 0; i < 100000; i++){arr[i] = (rand()%10000)+(134.234*i);std::cout<<"is"<<arr[i]<<std::endl;}int numelements = sizeof(arr)/sizeof(arr[0]);std::cout<<"num elements are"<<numelements*8;//multiplied by 8 is size of double;动态分配是好的,堆上的内存分配没有问题,但是strlen(buffer)吗?如果有人建议使用"num elements are" = 0,请建议我如何将其作为数组传递,因为std::vector<double>m_vector函数仅适用于文本数据,是吗?或者,如果有什么主意,我该如何计算元素的实际数量?请不要说m_vector.data()。我正在寻找一些合理的方法来做到这一点。 srand (time(0)); double *arr = new double[800010]; for(int i = 0; i < 100000; i++) { arr[i] = (rand()%10000)+(134.234*i); std::cout<<"is"<<arr[i]<<std::endl; } int numelements = sizeof(arr)/sizeof(arr[0]); std::cout<<"num elements are"<<numelements*8; 最佳答案 代替使用new[]分配数组,而使用std::vector。它将为您跟踪大小,并注意释放基础内存。例如:std::vector<double> arr(100000);for(int i = 0; i < arr.size(); i++){ arr[i] = (rand()%10000) + (134.234*i); std::cout << "is" <<arr [i] << std::endl;}int numelements = arr.size();关于c++ - 动态和静态分配的数组元素计算? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21625268/
10-10 14:06
查看更多