简体   繁体   English

C:分配结构的二维数组

[英]C: assign 2d array of struct

Background背景

I have a struct with two 2D arrays...我有一个带有两个二维数组的结构......

typedef struct v
{
    int *b;
    int *a;
} v;

Inside my main function I have...在我的主要功能中,我有...

int A [M][K] = {{2,2},{2,2}, {3,2} };
int B [K][N] = {{2,2,2},{2,2,2}};
struct v *data= (struct v *) malloc(sizeof(struct v));
data.a->A;
data.b->B;
pthread_create(&multiplicationWorker, NULL, (void *) &alterAarrays,  data);

...and a private function... ...和一个私人功能...

void alterArrays ( v* coords)
{
    ...
}

Question:题:

I want to pass references to the 2D arrays inside alterArrays .我想传递对alterArrays的二维数组的alterArrays Also it won't let me assign the values of the 2D arrays like this.它也不会让我像这样分配二维数组的值。 Any suggestions?有什么建议?

Define sizes:定义尺寸:

#define K 2
#define M 3
#define N 3

If you want to use arrays in your struct:如果要在结构中使用数组:

Define struct (did you mean to call these a and b ? You refer to them as this in the code. Also, the dimensions originally differed from the arrays in the code:定义结构体(你的意思是要调用这些ab吗?你在代码中将它们称为 this。另外,维度最初与代码中的数组不同:

typedef struct v
{
    int a [M][K];
    int b [K][N];
} v;

Then the copies:然后是副本:

int A [M][K] = {{2,2},{2,2}, {3,2} };
int B [K][N] = {{2,2,2},{2,2,2}};
struct v *data= (struct v *) malloc(sizeof(struct v));

memcpy(data->a, A, M * K * sizeof(int));
memcpy(data->b, B, K * N * sizeof(int));

If you want to use pointers in your struct:如果要在结构中使用指针:

Define struct:定义结构:

typedef struct v
{
    int (*a)[K];
    int (*b)[N];
} v;

And you need to make A and B global, so they are not on the stack.并且您需要将AB设为全局,因此它们不在堆栈中。 So define them at the top of your source file:因此,在源文件的顶部定义它们:

int A [M][K] = {{2,2},{2,2}, {3,2} };
int B [K][N] = {{2,2,2},{2,2,2}};

Then the assignment:然后是任务:

struct v *data= (struct v *) malloc(sizeof(struct v));

data->a = A;
data->b = B;

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

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