I have a function in C (my_malloc
is just a wrapper with testing if the allocation was suscessful):
#define MAXIMUM { \
int value = 0; \
for (int i = 0; i < n; i++) { \
if (value < (*numbers)[i]) {\
value = (*numbers)[i]; \
} \
} \
return value; \
}
int maximum1(int n, int **numbers) MAXIMUM;
int maximum2(int n, int (*numbers)[n]) MAXIMUM;
Then I call it like this (n
in some number of elements in an array):
int *numbers = my_malloc(n * sizeof(int *));
// array numbers is filled
int value = maximum1(n, &numbers);
and
int numbers[n];
// array numbers is filled
int value = maximum2(n, &numbers);
Can something be done with it to make it cleaner? I would like to only have one maximum function.
Here is where all the problems started:
int numbers[n];
//int *numbers = my_malloc(n * sizeof(int *));
// There is no way, I could find, to use dynamically allocated array...
// the pointer of numbers array changes after calling MPI_Recv...
// only a fixed array worked here, otherwise exactly two
// elements are received all the time...meh
//printf("address before: %p\n", numbers);
MPI_Recv(numbers, n, MPI_INT, 0, 0, MPI_COMM_WORLD, &status);
//printf("address after: %p\n", numbers); //<-- changing when using malloc
value = maximum2(n, &numbers);
// Copying contents of the static array to dynamically allocated
// one works (just maximum1 is required)
//int *numbers = my_malloc(n * sizeof(int *));
//for (i = 0; i < n; i++)
//numbers[i] = numbers_old[i];
//value = maximum1(n, &numbers);
The uncommented is current working state. The comments pose two working solutions:
- creating fixed array and copying its contents over to dynamically allocated one (just one maximum funciton is then needed but it is a stupid solution)
- using just the fixed array with maximum2 funciton
EDIT
After hours of headache it does magically appear to be working correctly, without the apparent change, so I am not sure what is going on....
The my_malloc
function:
void *my_malloc(size_t size) {
void *p = malloc(size);
if (p == NULL) {
printf("Memory allocation unsuccessful.\n");
exit(EXIT_FAILURE);
}
return p;
}