如何使数组的大小动态? [英] how to make size of an array dynamic?

查看:96
本文介绍了如何使数组的大小动态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

for(j=0;j<e1;j++)
{
index1=PZLoctn1[j];
index2=NZLoctn1[j];
printf("\n%d\t%d\n",index1,index2);
	
	for(i=index1;i<index2;i++)
		{
		   pz2nz[0][i]=kld_smooth_norm[i];
		  // printf("pz2nz:%f\n",pz2nz[0][i]);	
		}
		  
}



这里kld_smooth_norm [80,000]并且每个循环的index1 index2都会改变

第一循环index1 = 12612 index2 = 14521

第二循环index1 = 16029 index2 = 23753

第三循环index1 = 31387 index2 = 55794

第4循环index1 = 62933 index2 = 68856

和pz2nz我想存储每个循环的所有元素来自index1 t oindex2

有人可以告诉我如何声明大小pz2nz用于存储元素


here kld_smooth_norm[80,000] and the index1 index2 will be changing for each loop
first loop index1=12612 index2=14521
2nd loop index1=16029 index2 =23753
3rd loop index1=31387 index2= 55794
4th loop index1=62933 index2=68856
and in pz2nz i want to store all the element for each loop from index1 t oindex2
can someone tell me how to declare the size of pz2nz for storing the elements

推荐答案

不要使用数组,请使用集合类 [ ^ ]。





道歉我误读了C C#。你可以在运行时通过 malloc [ ^ ]。



[/ edit]
Don't use an array, use one of the Collection classes[^].

[edit]
Apologies I misread C for C#. You can make an array dynamic in C by allocating it at run time via malloc[^].

[/edit]


无法在C中声明一个数组,其大小为在编译时是未知的。相反,您可以使用malloc / free动态分配存储并将其地址分配给指针。



分配存储需要一些时间,建议避免分配/释放存储以高频率,例如在循环中。在你的情况下,似乎很容易:在第一个循环中确定所需的最大长度,然后分配一次存储。



这里的另一个观察,就是你看起来在每个循环中仅使用小的索引间隔,例如62933 ... 68856.在这种情况下,只需为该索引间隔分配一个数组,在这种情况下为5924个单元格,并重新计算您访问的索引那个数组。



在C ++中,工作会更容易,因为你可以使用像vector这样的类,它可以为你做很多的存储管理。
There is no way to declare an array in C, the size of which is unknown at compile-time. Instead you can use malloc / free to allocate storage dynamically and assign its address to a pointer.

Allocating storage takes some time and it is advisable to avoid allocating / freeing storage in a high frequency, for example in a loop. In your case that seems to be possible easily: Determine in a first loop the maximum length needed and then allocate that storage once.

Another observation here, is that you seem to use only small index intervals in each loop, for example 62933 ... 68856. In such a case it may pay off to just allocate an array for that index interval, 5924 cells in that case, and recalculate the index with which you access that array.

In C++ the job would be somewhat easier as you could make use of classes like vector, which does much the storage management for you.


这篇关于如何使数组的大小动态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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