Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a 2D array by pointer in C?

Tags:

arrays

c

pointers

I am learning C and am having trouble passing the pointer of a 2D array to another function that then prints the 2D array. Any help would be appreciated.

int main( void ){     char array[50][50];     int SIZE;      ...call function to fill array... this part works.      printarray( array, SIZE ); }  void printarray( char **array, int SIZE ){     int i;     int j;      for( j = 0; j < SIZE; j++ ){         for( i = 0; i < SIZE; i ++){             printf( "%c ", array[j][i] );         }         printf( "\n" );     } } 
like image 594
user1362058 Avatar asked May 23 '13 21:05

user1362058


People also ask

Can you pass a 2D array in C?

// The following program works only if your compiler is C99 compatible. If compiler is not C99 compatible, then we can use one of the following methods to pass a variable sized 2D array. In this method, we must typecast the 2D array when passing to function.

Can you pass an array as a pointer in C?

Array can be passed to function in C using pointers and because they are passed by reference changes made on an array will also be reflected on the original array outside function scope.

Can you pass an array by pointers?

A whole array cannot be passed as an argument to a function in C++. You can, however, pass a pointer to an array without an index by specifying the array's name.


1 Answers

char ** doesn't represent a 2D array - it would be an array of pointers to pointers. You need to change the definition of printarray if you want to pass it a 2D array:

void printarray( char (*array)[50], int SIZE ) 

or equivalently:

void printarray( char array[][50], int SIZE ) 
like image 94
Carl Norum Avatar answered Sep 21 '22 17:09

Carl Norum