如何使用未知的指针和长度对数组进行迭代

How to iterate over a array using a pointer and length unknown?

本文关键字:数组 迭代 未知 何使用 指针      更新时间:2023-10-16

我得到了一个可以使用的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::vectorstd::array而不是手动分配的数组的原因之一;尽管这对你没有帮助,因为尽管有问号,你在这里使用的是C。

int len=sizeof(sampleState)/sizeof(short);
int len=sizeof(samplePosition)/sizeof(int);

sizeof是在编译时完成的,因此如果在编译时数组的长度未知(例如,使用malloc保留内存),则这种方法不起作用。

好的,忽略我上面使用的方法,这都是错误的-尽管你需要知道我最终从API开发人员那里得到的数组的长度。