i have a question for you!
I have a C program in which i have a dynamic 2d array in my main function:
int **neighbours;
which i initialize based on args from command line.
The problem is that i want to clean up the code a bit. To do that i want to create a function in a header file that takes the array uninitialized as a reference argument and initialize it there.
This is how i call the function:
init(&nodeNum, &neighbours, argv[1], &nodes);
this is how i declare the function in the header file:
int init(int *nodeNum, int ***neighbours, char *arg, struct node **nodes)
and this is how try to allocate the memory:
neighbours=malloc(*nodeNum*sizeof(int *));
for(i=0;i<*nodeNum;i++){
neighbours[i] = malloc(*nodeNum*sizeof(int *));
}
well obviously something doesn’t go well and it crashes! any hints on what i may be doing wrong?
thanks to the help of some nice people the malloc now works, but filling the nodes failes!
here is the whole code of the function:
int init(int *nodeNum, int ***neighbours, char *arg, struct node **nodes){
FILE *file;
char buffer[4];
int i,y,distance;
if(strcmp(arg,"-l")==0){
file = fopen("C:\\Users\\trendkiller\\thesis\\matrix.txt","r");
printf("parsing adjacency matrix from file\n\n");
//file = fopen ("C:\\Users\\trendkiller\\thesis\\matrix.txt", "r" ) ;
*nodeNum = atoi(fgets(buffer,4,file));
*neighbours=malloc(*nodeNum*sizeof(int *));
for(i=0;i<*nodeNum;i++){
(*neighbours)[i] = malloc(*nodeNum*sizeof(int *));
}
printf("this prints\n");
printf("number of nodes: %s", buffer);
for(i=0;i<*nodeNum;i++){
for(y=0;y<*nodeNum;y++){
fgets(buffer,4,file);
(*neighbours)[i][y]=atoi(buffer);
}
}
}
else{
*nodeNum = atoi(arg);
*neighbours=malloc(*nodeNum*sizeof(int *));
printf("this prints\n");
for(i=0;i<*nodeNum;i++){
(*neighbours)[i] = malloc(*nodeNum*sizeof(int *));
}
*nodes=malloc(*nodeNum*sizeof(struct node));
for(i=0;i<30;i++){
(*nodes)[i].x=rand()%100;
(*nodes)[i].y=rand()%100;
}
printf("this prints\n");
printf("creating new adjacency matrix\n\n");
for(i=0; i<*nodeNum; i++){
for(y=0; y<*nodeNum; y++){
distance=sqrt((((*nodes)[y].x-(*nodes)[i].x)*((*nodes)[y].x-(*nodes)[i].x))+(((*nodes)[y].y-(*nodes)[i].y)*((*nodes)[y].y-(*nodes)[i].y)));
if(i==y){
(*neighbours)[i][y]=-1;
}
else if(distance<=20){
(*neighbours)[i][y]=1;
}
else {
(*neighbours)[i][y]=0;
}
}
}
file = fopen("C:\\Users\\trendkiller\\thesis\\matrix.txt","a+");
fprintf(file,"%d\n",*nodeNum);
for(i=0;i<*nodeNum;i++){
for(y=0;y<*nodeNum;y++){
fprintf(file,"%d\n", (*neighbours)[i][y]);
}
}
}
return 0;
}
Thanks in advance for your help!
The problem is that
neighboursis passed by value, so modifications to it inside the function have no effect. You need to pass it by pointer, and modify it indirectly:You also need to pass
&neighboursinstead ofneighboursas the second argument ofinit.