如何使用未知的指针和长度对数组进行迭代
How to iterate over a array using a pointer and length unknown?
我得到了一个可以使用的c api和最少的文档。开发人员现在不在,他的代码返回了意外的值(数组不是预期长度)
我对返回数组指针的方法有问题,我想知道我是否正确地迭代了它们。
Q: 以下总是返回数组的正确len吗?
int len=sizeof(sampleState)/sizeof(short);
int len=sizeof(samplePosition)/sizeof(int);
typedef unsigned char byte;
int len=sizeof(volume)/sizeof(byte);
我使用指针和指针算法迭代数组(我对下面的所有类型都做得正确吗)
下面的最后一个例子是多维数组?对此进行迭代的最佳方法是什么?
感谢
//property sampleState returns short[] as short*
short* sampleState = mixerState->sampleState;
if(sampleState != NULL){
int len=sizeof(sampleState)/sizeof(short);
printf("length of short* sampleState=%dn", len);//OK
for(int j=0;j<len;j++) {
printf(" sampleState[%d]=%un",j, *(sampleState+j));
}
}else{
printf(" sampleState is NULLn");
}
//same with int[] returned as int*
int* samplePosition = mixerState->samplePosition;
if(samplePosition != NULL){
int len=sizeof(samplePosition)/sizeof(int);
printf("length of int* samplePosition=%dn", len);//OK
for(int j=0;j<len;j++) {
printf(" samplePosition[%d]=%dn",j, *(samplePosition+j));
}
}else{
printf(" samplePosition is NULLn");
}
这里的字节是的def类型
typedef unsigned char byte;
所以我用了%u
//--------------
byte* volume = mixerState->volume;
if(volume != NULL){
int len=sizeof(volume)/sizeof(byte);
printf("length of [byte* volume = mixerState->volume]=%dn", len);//OK
for(int j=0;j<len;j++) {
printf(" volume[%d]=%un",j, *(volume+j));
}
}else{
printf(" volume is NULLn");
}
这是int[][] soundFXStatus
。
我只是使用上面相同的方法并有两个循环吗?
//--------------
int** soundFXStatus = mixerState->soundFXStatus;
sizeof(array)/sizeof(element)
技巧只有在有实际数组而不是指针的情况下才有效。如果你只有一个指针,就没有办法知道数组的大小;必须将数组长度传递到函数中。
或者最好使用具有size
功能的vector
。
sizeof(sampleState)/sizeof(short);
如果sampleState
被声明为数组,而不是指针,这将仅给出数组的长度:
short array[42];
sizeof(array)/sizeof(short); // GOOD: gives the size of the array
sizeof(array)/sizeof(array[0]); // BETTER: still correct if the type changes
short * pointer = whatever();
sizeof(pointer)/sizeof(short); // BAD: gives a useless value
另外,要注意,函数参数实际上是指针,即使它看起来像一个数组:
void f(short pointer[]) // equivalent to "short * pointer"
{
sizeof(pointer)/sizeof(short); // BAD: gives a useless value
}
在您的代码中,sampleState
是一个指针;如果只有一个指向数组的指针,就无法确定数组的长度。API可能提供了一些获取长度的方法(因为否则它将不可用),您需要使用它。
在C++中,这就是为什么您更喜欢std::vector
或std::array
而不是手动分配的数组的原因之一;尽管这对你没有帮助,因为尽管有问号,你在这里使用的是C。
int len=sizeof(sampleState)/sizeof(short);
int len=sizeof(samplePosition)/sizeof(int);
sizeof是在编译时完成的,因此如果在编译时数组的长度未知(例如,使用malloc保留内存),则这种方法不起作用。
好的,忽略我上面使用的方法,这都是错误的-尽管你需要知道我最终从API开发人员那里得到的数组的长度。
相关文章:
- 如何以优化的方式同时迭代两个间距不相等的数组
- 为什么我的 scanf() 没有在我的数组上迭代我的 for 循环?
- 迭代器库中的 std::size() 不适用于传递给函数的 C 样式数组
- 自定义 STL 兼容迭代器,用于迭代 2D 数组类的列
- 在C++中使用 for 循环的数组迭代
- 如何使用基于范围的for循环迭代Rapidjson文档(它本身就是一个JSON数组)
- 获取 c++ 中具有恒定长度的数组的迭代器
- 指针到指针 2-D 数组中的迭代
- 如何通过引用对用户定义对象的类型集 (STL) 的数组元素进行增强迭代?
- 为自定义数组实现迭代器
- 数组迭代器不是可取消引用的错误
- 元素级多维数组迭代,与存储顺序无关
- 多维数组迭代效率
- std::不带模板的数组迭代器范围
- 在多线程代码中缓存友好的数组迭代模式
- 用1个循环解释二维数组迭代
- 可变模板形参和元组迭代
- 数组迭代器中的hasNext()方法
- 兼容STL的两个数组迭代器
- 对于循环数组迭代,if循环测试索引是否为真/假,计算结果不正确