Thread: 2-d memory allocation and its arg passing

  1. #1
    Registered User
    Join Date
    Nov 2008
    Posts
    2

    2-d memory allocation and its arg passing

    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!

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,613
    Let's try this again:
    int ** ord_k = malloc( k * sizeof(int*) );

    gives you an array of k integer pointers. Each of these pointers would need to be calloc'd a segment of memory if you want a matrix out of ord_k. Does it make sense now? Don't mix up the operators for assignment and equality.

  3. #3
    Registered User
    Join Date
    Nov 2008
    Posts
    2
    Thanks... guess it turned out to be a really silly mistake!

Popular pages Recent additions subscribe to a feed