2

You can't pass arrays by value in c, so pointers must be used? Here is the code:

#include <stdio.h>

#define N 5
void printArray(int array[N][N]) {
    for(int i = 0;i < N;i++) {
        for(int j = 0;j < N;j++) {
            printf("%d", &array[i][j]);
        }
    }
}

int main() {
    int array[N][N];

    for(int i = 0;i < N;i++) {
        for(int j = 0;j < N;j++) {
            array[i][j] = 8;
        }
    }

    printArray(array);
    return 0;
}

What actually happens when the program is compiled?

Is it the same as doing this?

#include <stdio.h>

define N 5
void printArray(int* array, int rows, int cols) {
    for(int i = 0;i < rows;i++) {
        for(int j = 0;j < cols;j++) {
            printf("%d", &array[i * cols + j]);
        }
    }
}

int main() {
    int array[N][N];

    for(int i = 0;i < N;i++) {
        for(int j = 0;j < N;j++) {
            array[i][j] = 8;
        }
    }

    printArray(&array[0][0], N, N);
    return 0;
}
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
adsf
  • 59
  • 5
  • 1. Your `printf("%d", &a...` are wrong, remove the `&`. 2. You should fill the array with different numbers, not only with `8`s. 3. Did you run both programs? – Jabberwocky Dec 09 '22 at 16:55
  • The second program has undefined behaviour. You cannot flatten 2D arrays in C this way. – n. m. could be an AI Dec 09 '22 at 16:55
  • Welcome to the wild world of [pointer decay](https://stackoverflow.com/questions/1461432/what-is-array-to-pointer-decay). – tadman Dec 09 '22 at 17:06

1 Answers1

1

If an array is declared to be a parameter to a function, it is adjusted to be a pointer to an element of the array.

In the case of int array[N][N], you have an array of size N, and each element of that array is an array of size N of int. This means a 2D array decays to a pointer to a 1D array.

So this:

void printArray(int array[N][N]) {

Is actually this:

void printArray(int (*array)[N]) {

And can be indexed the same way.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • What does the parenthesis around (*array) mean in void printArray(int (*array)[N]) ? – adsf Dec 09 '22 at 17:07
  • When declaring the function like this, do you pass the pointer to the first element of the 2d array to the function? – adsf Dec 09 '22 at 17:08
  • @adsf It groups the `*` with the name `array` instead of with `array[N]`. `int (*array)[N]` is a pointer to an array of `int` while `int *array[N]` is an array of pointers to `int`. The call would be the same, i.e. `printArray(array);`. – dbush Dec 09 '22 at 17:09
  • Isn't "int *array" also a pointer to an array of int? And is "&array[0][0]" passed to the function? – adsf Dec 09 '22 at 18:36
  • @adsf No, `int *array` is a pointer to an `int`, not an array of `int`, and `&array[0]` is what gets passed to the function i.e. a pointer to the first element of the array. – dbush Dec 09 '22 at 18:38