gpt4 book ai didi

c - 遍历不同的数组C

转载 作者:行者123 更新时间:2023-11-30 19:25:17 25 4
gpt4 key购买 nike

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


所以我有一个函数调用,看起来像这样:

(*f)(array512, n512);


但是我希望我的程序使用所有这些数组和上面定义的相应整数来迭代函数调用。整数是相应数组的大小。

我试图找到一些解决方案。是否可以使用“指针”迭代具有不同变量的函数调用?

最佳答案

该方法的草稿使用了一个struct数组,其成员扮演了离散函数指针参数所扮演的角色。我的希望是,这可以说明某些评论所暗示的内容:

注意,由于此示例使用struct数组,因此您的函数指针为:

(*f)(array512, n512);  


看起来像:

int (*f_ptr)(STRUCT_ARRAY *arr);  


查看内联评论以获取解释...

   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;
f_array[1] = &f_2;
//...
f_array[N_MAX-1] = &f_<value of N_MAX>
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;
}
//...
int f_<value of N_MAX - 1>((STRUCT_ARRAY *arr)
{
//....
}


注意,如果还将在函数中创建内存,则在不再需要时将需要释放内存。

关于c - 遍历不同的数组C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59076998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com