如何使用指针和长度未知来迭代数组?

bri*_*ear 5 c c++ arrays pointers multidimensional-array

我已经获得了ac api和最低限度的文档.开发人员目前不在,他的代码返回了意外的值(数组不是预期的长度)

我有返回指向数组指针的方法的问题,并想知道我是否正确迭代它们.

问:以下是否始终返回数组的正确len?

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

 typedef unsigned char byte;
 int len=sizeof(volume)/sizeof(byte);
Run Code Online (Sandbox Code Playgroud)

我使用指针和指针算法迭代数组(我正在为下面的所有类型正确地做)

以下最后一个例子是多维数组?什么是迭代这个的最好方法?

谢谢

//property sampleState returns short[] as short* 

    short* sampleState = mixerState->sampleState;
    if(sampleState != NULL){
        int len=sizeof(sampleState)/sizeof(short);
        printf("length of short* sampleState=%d\n", len);//OK

        for(int j=0;j<len;j++) {
            printf("    sampleState[%d]=%u\n",j, *(sampleState+j));                
        }
    }else{
        printf("    sampleState is NULL\n"); 
    }

//same with int[] returned as  int*     

    int* samplePosition = mixerState->samplePosition;
    if(samplePosition != NULL){
        int len=sizeof(samplePosition)/sizeof(int);
        printf("length of int* samplePosition=%d\n", len);//OK

        for(int j=0;j<len;j++) {
            printf("    samplePosition[%d]=%d\n",j, *(samplePosition+j));                
        }
    }else{
        printf("    samplePosition is NULL\n"); 
    }
Run Code Online (Sandbox Code Playgroud)

这里的字节是def到的类型

typedef unsigned char byte;
Run Code Online (Sandbox Code Playgroud)

所以我使用%u

    //--------------
    byte* volume    = mixerState->volume;

    if(volume != NULL){
        int len=sizeof(volume)/sizeof(byte);
        printf("length of [byte* volume = mixerState->volume]=%d\n", len);//OK

        for(int j=0;j<len;j++) {
            printf("    volume[%d]=%u\n",j, *(volume+j));                
        }
    }else{
        printf("    volume is NULL\n"); 
    }
Run Code Online (Sandbox Code Playgroud)

这是int[][] soundFXStatus.

我只是使用上面的相同方法,并有2个循环?

    //--------------
    int** soundFXStatus         = mixerState->soundFXStatus;
Run Code Online (Sandbox Code Playgroud)

Mar*_*som 10

sizeof(array)/sizeof(element)只有当你有一个实际的数组而不是指针时,这个技巧才有效.有没有办法知道数组的大小,如果你已经是一个指针; 您必须将数组长度传递给函数.

或者更好地使用a vector,它具有一个size功能.