1

I have the following struct:

typedef struct {
  int row;
  int** matrix;
} values ;

To fill the struct matrix I tried the following code:

values **v = (values **)malloc(x * sizeof(values *));
for (int z = 0; z < y; ++z)
     [z] = (values *)malloc(y * sizeof(values));

Where x is the number of rows and y columns.

How can I populate the arguments (row and matrix) of struct and pass as parameter to a function called by pthread? Something similar to...

pthread_create(&thread1, NULL, somaLinha, v);
Mathiasfc
  • 1,627
  • 1
  • 16
  • 24
  • The line starting `values **v` defines a pointer to an array of pointers to your `value` struct (which could eventually be treated as a '2D array' of structures). You then allocate an array of size `y` structures for each row of the matrix. But none of this has done anything about the matrix embedded in each of the structures. Are you sure that's what you wanted? – Jonathan Leffler Sep 05 '18 at 03:12

1 Answers1

2

When you allocate the space for the struct, C is actually going to allocate the space for an integer plus the space for the pointer (which is 4+8 bytes)

You need to allocate the space for the struct, and then allocate for the matrix

values *v = (values *) malloc(sizeof(values));
v->matrix = (int **) malloc(y * sizeof(int *));
for (int z = 0; z < y; ++z)
    v->matrix[z] = (int *) malloc(y * sizeof(int));

And then you create the thread

pthread_create(&thread1, NULL, somaLinha, v);
gmelodie
  • 411
  • 4
  • 18
  • Thanks a lot. Would you know how to fill the value of the row in the struct as well? And just to confirm, the function declaration looks like this: `void * somaLinha(v values)`? – Mathiasfc Sep 05 '18 at 11:55
  • 1
    As I believe this discussion does not directly refer to the question, I sent you an email with the answer. – gmelodie Sep 05 '18 at 14:47
  • @MathiasFalci: Note that all thread 'main' functions should have the signature `void *function(void *data);` (the name of the function and the argument is variable; the type information is not). Your `somaLinha()` should therefore have the declaration `void *someLina(void *data)`. Inside the function, you can use `values *vp = data;` or equivalent to get the pointer to the matrix. The `pthread_create()` call is then OK. You need to decide whether the thread launching code or the thread main function (`somaLinha`) releases the allocated space; it's usually best if the launch code cleans up. – Jonathan Leffler Sep 05 '18 at 19:10