Using pointer defined in a header function
Hi there,
I have two files, func2.h and main.c. In func2.h I have a function, network_construction, where I dynamically allocate and assign values to a pointer, veins, which pretends to be a two dimensional matrix with rows of different length. In main.c there is the declaration of this pointer.
I am finding problems in dealing with the allocation of memory and filling the values only inside the function network_construction. I want to use veins in main.c for later calculations, but before calling the function in main.c ,it shouldn't appear any reference to veins, only the declaration. The files are below, but so far I have been obtaining Segmentation faults. How do I overcome these errors ? What am I doing wrong ?
main.c:
Code:
#include <stdio.h>
#include <stdlib.h>
#include "func2.h"
void main(){
int num_veins[NN];
int **veins;
network_construction(&veins, num_veins);
printf("\n%d\n", veins[2][2]);
for (i = 0; i < NN; i++) {
free(veins[i]);
}
free(veins);
return;
}
func2.h
Code:
#define NN 20
void network_construction(int ***veins, int *num_veins){
int i, j;
for(i=0;i<NN;i++){
num_veins[i] = NN/2;
}
*veins = malloc(NN * sizeof(*veins));
for (i = 0; i < NN; i++) {
*veins[i] = malloc(num_veins[i] * sizeof(**(veins[i])));
}
for (i = 0; i < NN; i++) { for (j = 0; j<num_veins[i];j++) { *veins[i][j] = -1; } }
return;
}
Any solution would be really appreciated. Thank you in advance !