简体   繁体   English

遍历不同的数组C

[英]Iterate through different arrays C

int array512[512], array1024[1024], array2048[2048], array4096[4096],  array8192[8192], array16384[16384];
int n512, n1024, n2048, n4096, n8192, n16384;

So I have a function call that looks like this: 所以我有一个函数调用,看起来像这样:

(*f)(array512, n512);

But I want my program to iterate the function call with all of those arrays and the corresponding integer defined above. 但是我希望我的程序使用所有这些数组和上面定义的相应整数来迭代函数调用。 The integers are the corresponding arrays' sizes. 整数是相应数组的大小。

I tried to find some solutions. 我试图找到一些解决方案。 Is it possible to use "pointers" to iterate the function call with different variables? 是否可以使用“指针”迭代具有不同变量的函数调用?

This rough draft of an approach uses an array of struct , its members performing the role that your discrete function pointer arguments did. 方法的草稿使用struct数组,其成员执行离散函数指针参数所做的角色。 My hope here is that this may illustrate what some of the comments are suggesting: 我的希望是,这可以说明某些评论所暗示的内容:

Note, because this example uses an array of struct, your function pointer: 注意,由于此示例使用struct数组,因此您的函数指针为:

(*f)(array512, n512);  

will look like: 看起来像:

int (*f_ptr)(STRUCT_ARRAY *arr);  

See comments inline for explanations... 查看内联评论以获取解释...

   typedef enum {
        N512 = 512,
        N1024 = 1024,
        /// and so on
        N16384 = 16384,
        N_MAX// bookkeeping - use N_MAX to create array sizes
    }SIZE;

int s_array[N_MAX] = {512, 1024, /* ...,*/ 16384};  



 typedef struct {
    int *arr;
    int arrSize;
}STRUCT_ARRAY;

typedef int (*f_ptr)(STRUCT_ARRAY *arr);
f_ptr f_array[N_MAX];

// prototypes of functions  
int f_1(STRUCT_ARRAY *arr);
int f_2(STRUCT_ARRAY *arr);
// and so on...
int f_n(STRUCT_ARRAY *arr);

STRUCT_ARRAY *array_t;
int main(void)
{
    f_array[0] = &f_1;
    array_t = calloc(N_MAX, sizeof(*array_t));//memory for struct
   // check for success here
    for(int i=0; i<N_MAX; i++)
    {
        //call your function using array[i], and s_array[i] for arguments
        array_t[i].arr = calloc(s_array[i], sizeof(int));
        f_array[i](&array_t[i]);
        // use it as needed
    }
    //free allocated memory memory

    return 0;
}

int f_1(STRUCT_ARRAY *arr)
{
    // this is 1 of N_MAX "definitions" that your array of function pointers will point to.
    //(create the others)
    // you will need to populate with the code as per your requirements
    // including allocating and freeing memory as needed.

    return 0;   
}

Note, if memory will be created in your function as well, then will need to be freed when no longer needed. 注意,如果还将在函数中创建内存,则在不再需要时将需要释放内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM