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

In main(), the variable "array" is declared as

char array[50][50];

This is a 2500 byte piece of data. When main()'s "array" is passed about, it is a pointer to the beginning of that data. It is a pointer to a char expected to be organized in rows of 50.

Yet in function printarray(), you declare

 char **array

"array" here is a pointer to a char *pointer.

@Lucus suggestion of void printarray( char array[][50], int SIZE ) works, except that it is not generic in that your SIZE parameter must be 50.

Idea: defeat (yeech) the type of parameter array in printarray()

void printarray(void *array, int SIZE ){
    int i;
    int j;
    char *charArray = (char *) array;

    for( j = 0; j < SIZE; j++ ){
        for( i = 0; i < SIZE; i ++){
            printf( "%c ", charArray[j*SIZE + i] );
        }
        printf( "\n" );
    }
}

A more elegant solution is to make the "array" in main() an array of pointers.

// Your original printarray()
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" );
    }
}

// main()
char **array;
int SIZE;
// Initialization of SIZE is not shown, but let's assume SIZE = 50;
// Allocate table
array = (char **) malloc(SIZE * sizeof(char*));
  // Note: cleaner alternative syntax
  // array = malloc(sizeof *array * SIZE);
// Allocate rows
for (int row = 0; row<SIZE; row++) {
  // Note: sizeof(char) is 1. (@Carl Norum)
  // Shown here to help show difference between this malloc() and the above one.
  array[row] = (char *) malloc(SIZE * sizeof(char));
    // Note: cleaner alternative syntax
    // array[row] = malloc(sizeof(**array) * SIZE);
  }
// Initialize each element.
for (int row = 0; row<SIZE; row++) {
  for (int col = 0; col<SIZE; col++) {
    array[row][col] = 'a';  // or whatever value you want
  }
}
// Print it
printarray(array, SIZE);
...

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 )

Tags:

C

Arrays

Pointers