Following is the piece of code where memory is allocated to a 2-d array "ord_k" dynamically
Code:
int main(int argc, char* argv[])
{
int k = 5;
if (argc!=4)
{
fprintf(stderr, "Usage: get_best_net nof_vars sinkfile ordfile\n");
return 1;
}
{
int nof_vars = atoi(argv[1]);
char* ord = malloc(nof_vars*sizeof(char));
int** ord_k = malloc(k * sizeof(int*));
int k_i = 0;
for(k_i=0; k_i<k; k_i++)
{
ord_k[k_i] == (int*)calloc(nof_vars,sizeof(int));
}
get_best_order(nof_vars, argv[2], ord, ord_k, k);
{
FILE* ordf = fopen(argv[3], "w");
int i;
for(i=0;i<nof_vars;++i)
{
fprintf(ordf, "%d%c", ord[i], i==nof_vars-1 ? '\n' : ' ');
}
fclose(ordf);
}
}
return 0;
}
following is the function to which argument ord_k is being passed to
Code:
void get_best_order(int nof_vars, char* sinkfile, char* ord, int** ord_k, int k)
{
...
ord_k[0][0] = 1; // gives segmentation fault
...
}
Even when i try to print in GDB, it evaluates ord_k[0] first, takin its value = 0 , then errors like for ord_k[0][0]
0x4 address can not be accessed.
At the same time if i treat it like a 1-D array, it works fine, i.e. ord_k[24] is ok and = 0
Please help as to where is the problem in accessing the array as 2D.
Thanks!