2

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. Also it won't let me assign the values of the 2D arrays like this. Any suggestions?

1
  • data.a->A; That isn't valid and wouldn't do anything useful even if it were Commented Oct 21, 2012 at 21:12

1 Answer 1

2

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:

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. 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;
Sign up to request clarification or add additional context in comments.

2 Comments

Will this change the values of A and B? because that is what I want. Seems to me like a copy would not do so
No. If you want to change A and B, then you need to use pointers in the struct, rather than arrays. Also, you should either make A and B global, or put them on the heap.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.