Thread: Help with passing multidimensional array to function by ref.

  1. #1
    Registered User
    Join Date
    Nov 2007
    Posts
    3

    Help with passing multidimensional array to function by ref.

    Hey

    Here is code one:
    Code:
    int main() {
    	int i, j;
    	int **matriz;
    	// alocando espaço para as colunas
    	matriz = (int **)malloc(N*sizeof(int *));
    	// alocando espaço para as linhas, uma de cada vez
    	for (i=0;i<N;i++)
    		matriz[i] = (int *)malloc(N*sizeof(int ));
    	// inserindo n&#250;meros na matriz
    	for (j=0;j<N;j++)
    		for (i=0;i<N;i++)
    	      matriz[i][j] = 0;
    }
    Now what i am trying to do is this:

    Code:
    void criaMatriz(int** *matriz, int N);
    
    void criaMatriz(int** *matriz, int N) {
    	int i, j;
    	// alocando espa&#231;o para as colunas
    	*matriz = (int **) malloc(N*sizeof(int *));
    	// alocando espa&#231;o para as linhas, uma de cada vez
    	for (i=0;i<N;i++)
    		*(matriz[i]) = (int *) malloc(N*sizeof(int));
    	// inserindo n&#250;meros na matriz
    	for (j=0;j<N;j++)
    		for (i=0;i<N;i++)
    	      matriz[i][j] = 0;
    }
    int main {
               ...
               criaMatriz(&matriz, N);
    }
    But i'm getting segfaults. Clearly i'm passing it (&matriz) the wrong way, or i'm making mistakes inside the function. the error occurs in the line
    Code:
    *(matriz[i]) = (int *) malloc(N*sizeof(int));
    Any help is appreciated
    Last edited by PatrickSteiger; 11-19-2007 at 02:16 PM.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > *(matriz[i]) = (int *) malloc(N*sizeof(int));
    1. Don't cast malloc in a C program, see the FAQ.

    2. You have to be really careful with the dereferencing and precedence here.
    This should be
    (*matriz)[i] = malloc(N*sizeof(int));

    Likewise, later on
    (*matriz)[i][j] = 0;

    The initial call is fine.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Nov 2007
    Posts
    3
    Uh.. dull sintax errors

    I will take more attention next time

    Thank you very much!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 05-13-2011, 08:28 AM
  2. Compiling sample DarkGDK Program
    By Phyxashun in forum Game Programming
    Replies: 6
    Last Post: 01-27-2009, 03:07 AM
  3. Replies: 7
    Last Post: 11-21-2008, 04:27 PM
  4. function passing argument..array ?
    By jochen in forum C Programming
    Replies: 2
    Last Post: 09-30-2007, 11:53 AM
  5. passing array of structures to function
    By bvnorth in forum C Programming
    Replies: 3
    Last Post: 08-22-2003, 07:15 AM