:d
我的问题是我必须将更大的数组划分为更小的固定大小数组。我只是想知道分割数组的最佳方法是什么。我在这里看到了一个问题并从中得出了一个方法。阵列的数量正在发生变化。指数是我指向指针的数组。
int *ptr[num];//array of pointers
ptr[0] = indices;//points the first pointer in the first element of the array
for (y = 1; y <= num; y++) {
ptr[y] = ptr[y-1] + Size;//points the next pointer to it's position.
}
我想问的是我的方法是否正确?如果有替代解决方案来划分阵列。顺便说一下,我要传递小阵列。
答案 0 :(得分:1)
我通常会尝试避免循环,其中每次迭代的结果取决于前一次迭代。
int *ptr[num];//array of pointers
ptr[0] = indices;//points the first pointer in the first element of the array
for (y = 1; y < num; y++) {
ptr[y] = ptr[0] + y*Size;//points the next pointer to it's position.
}
原因是如果有人改变了y
的起始值,那么循环就会被破坏。例如,如果您决定永远不会使用ptr[1]
,则可以在2开始y
。这似乎是正确的,但ptr[2]
将被分配给ptr[1]
初始化了。
对于这样一个简单的循环,你正在做的事情很好。
你没有提到你打算如何使用这些指针但是如果它是这样的:
for(ii = 0; ii < num; ++ii)
myFunction(ptr[ii]);
然后直接使用'indicies'可能更简单:
for(ii = 0; ii < num; ++ii)
myFunction(indicies + ii*Size);
或者这样:
for(ii = 0; ii < num; ++ii)
myFunction(indicies[ii*Size]);
答案 1 :(得分:0)
一些小修正使用小于而不是小于或等于+你必须计算大小,
int *ptr[num];//array of pointers
ptr[0] = indices;//points the first pointer in the first element of the array
for (y = 1; y < num; y++) {
ptr[y] = ptr[y-1] + Size;//points the next pointer to it's position.
}
现在这个方法实际上不会划分数组,但会创建指向数组内部位置的指针。您无法单独删除新的划分子阵列。您只能删除较大的数组。此解决方案比将较大的阵列复制到较小的子阵列具有更好的性能。