Thread: Dynamically allocating 2D arrays within a function

  1. #1
    Registered User
    Join Date
    Jun 2007
    Posts
    26

    Dynamically allocating 2D arrays within a function

    I'm trying to dynamically allocate a 2D array within a function. I have the code working perfectly if I do the allocation in main. It compiles fine within the function but when I run the code I get the error "program has exited due to signal 10 (SIGBUS)" when i try to run it through xcode and I get "bus error" when I compile it through gcc and try to run it.

    Code:
    void CreateData(int numDataPts, int numClusters, int Length_data, Node** head, double*** centers)
    {
    	int i,j;
    
    	//Dynamically Create 2D arrays to hold Cluster Centers
    	*centers = (double**)malloc(sizeof(double)*numClusters);
    	for(i=0; i<numClusters; i++)
    		*centers[i] = (double*)malloc(sizeof(double)*Length_data);	//This line is where the error occurs
    
    
    	//Randomly initialize centers
    	for(i=0; i<numClusters; i++)
    		for(j=0; j<Length_data; j++)
    				*centers[i][j]=decRand()*2-1;
    		
    }
    note: centers is declared as
    Code:
    double** centers;
    and the function call is
    Code:
    	CreateData(numDataPts,numClusters,Length_data,&head,&centers);
    .
    Last edited by moddinati; 06-20-2007 at 11:41 AM. Reason: fixed a couple mistakes

  2. #2
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    probably (*centers)[i]
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  3. #3
    Registered User
    Join Date
    Jun 2007
    Posts
    26
    that was it, thanks

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. In over my head
    By Shelnutt2 in forum C Programming
    Replies: 1
    Last Post: 07-08-2008, 06:54 PM
  2. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  3. <Gulp>
    By kryptkat in forum Windows Programming
    Replies: 7
    Last Post: 01-14-2006, 01:03 PM
  4. 2D Dynamically allocated pointer arrays
    By Lionmane in forum C Programming
    Replies: 37
    Last Post: 06-11-2005, 10:39 PM
  5. Interface Question
    By smog890 in forum C Programming
    Replies: 11
    Last Post: 06-03-2002, 05:06 PM