I want to fill 2d array of struct with all 0. Firstly, I defined size of 2d array with define macro. As follows:
#define VECLEN 4
I have struct as follows:
struct args
{
int size;
int array[VECLEN][VECLEN];
};
However, I want to get the size of my 2d array from user but I couldn't dynamically give the size of 2d array.
I use multithread functionality with pthread_create using 2 threads. I have to call fill function twice with multithread. When I fill the input array with defined size(4), I can easily get desired output as follows:
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
However, I got weird result, when I want to fill 6*6 array as follows:
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 154148873 537473056 824183088
537473056 825636144 892483616 825635638 537474100
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define VECLEN 4
pthread_mutex_t myMutex;
struct args
{
int size;
int array[VECLEN][VECLEN];
};
void fill(void *input)
{
int size = ((struct args *)input)->size;
for (int j = 0; j < size; j++)
{
for (int i = 0; i < size; i++)
{
((struct args *)input)->array[i][j] = 0;
}
}
}
int main()
{
struct args *arguments = (struct args *)malloc(sizeof(struct args));
int number;
printf("please enter the size : ");
scanf("%d", &number);
arguments->size = number;
pthread_t threads[2];
pthread_mutex_init(&myMutex, NULL);
for (int i = 0; i < 2; i++)
pthread_create(&threads[i], NULL, fill, (void *)arguments);
for (int i = 0; i < 2; i++)
pthread_join(threads[i], NULL);
pthread_mutex_destroy(&myMutex);
for (int row = 0; row < number; ++row)
{
for (int col = 0; col < number; ++col)
printf("\t %d", arguments->array[row][col]);
printf("\n");
}
}