r/C_Programming • • 3d ago

i need your advice

Hey guys, I’ve run into a bit of a snag while learning C. I was looking at some source code (shown below) and noticed a function call that passes a pointer. However, the function receiving this pointer declares it as a two-dimensional array rather than as a pointer (like `int *name`). This is where I’m stuck—why declare it as a 2D array instead of as a pointer, the way you would for a 1D array?

#include <stdio.h>

// Function that displays a 2D array

// The number of columns (3) must be known at compile time

void afficherMatrice(int mat[][3], int lignes) {

for (int i = 0; i < lignes; i++) {

for (int j = 0; j < 3; j++) {

printf("%d ", mat[i][j]);

}

printf("\n");

}

}

// Alternative with both dimensions specified

void initialiserMatrice(int mat[2][3]) {

for (int i = 0; i < 2; i++) {

for (int j = 0; j < 3; j++) {

mat[i][j] = i * 10 + j;

}

}

}

int main() {

int matrice[2][3] = {{1, 2, 3}, {4, 5, 6}};

afficherMatrice(matrice, 2);

initialiserMatrice(matrice);

printf("\nAfter initialization:\n");

afficherMatrice(matrice, 2);

return 0;

}

(I think there is an error in this code)

0 Upvotes

9 comments sorted by

5

u/SmokeMuch7356 3d ago • Bravo

Remember that under most circumstances, an expression of type "array of T" will "decay" or evaluate to an expression of type "pointer to T" and the value of the expression will be the address of the first element of the array. When you call a function with an array parameter like

T a[N];
...
foo( a );

that's equivalent to writing

foo( &a[0] );

Since a[0] has type T, foo receives a value of type T *.

If we replace T with an array type R [M], we get:

+--T--+
|     |
v     v
R a[N][M];
...
foo( a );

which is still equivalent to

foo( &a[0] );

This time, a[0] has type R [M], so foo receives a value of type R (*)[M] (pointer to array of R).

In the context of a function parameter declaration, T a[N] and T a[] are "adjusted" to T *a. Similarly, declarations like R a[N][M] and R a[][M] are adjusted to R (*)[M].

6

u/ReallyEvilRob 3d ago

Help us help you by formatting your code.

2

u/tastygames_official 3d ago edited 3d ago

if you hit the "Aa" button in the bottom of the text box it opens up some controls to allow you to format code:

#include <stdio.h>

// Function that displays a 2D array
// The number of columns (3) must be known at compile time
void afficherMatrice(int mat[][3], int lignes) {
    for (int i = 0; i < lignes; i++) {
        for (int j = 0; j < 3; j++) {
            printf("%d ", mat[i][j]);
        }
        printf("\n");
    }
}

// Alternative with both dimensions specified
void initialiserMatrice(int mat[2][3]) {
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 3; j++) {
            mat[i][j] = i * 10 + j;
        }
    }
}

int main() {
    int matrice[2][3] = {{1, 2, 3}, {4, 5, 6}};
    
    afficherMatrice(matrice, 2);
    initialiserMatrice(matrice);
    printf("\nAfter initialization:\n");
    afficherMatrice(matrice, 2);
    
    return 0;
}

But technically in C you do not have arrays. You have pointers to the first element in an array, and you have to keep track of the length of the array yourself. The compiler can keep track of the "stride" of the array (how big each element is) by how you define its type, but really all it is is a series of data in memory.

So a type declaration of int[x][y] will simply be a series of x * y integers (probably 32-bit signed integers) in memory. But the variable you declare is really only just a pointer to the first element, and then you use the [x][y] to determine how far away from that starting memory address that particular element is.

/* this is just a pointer to an integer */
int *array;
/* now it's a pointer to the first of 10 integers */
array = malloc(sizeof(int) * 10);
/* this is how we get the 5th element (index 0 is the first) */
array[4];
/* this is essentially the same as above: a sequence of 10 integers */
int array1[10];

/* now we can have a multidimensional "array" aka matrix */
/* will be a 3x3 matrix, or simply a sequence of 9 ints */
int matrix[3][3];
/* we can address the third row, second column (or third column, second row - depending on how you view it) */
matrix[2][1];
/* this is the same as the 8th element in a simple list */
int matrix1[9];
matrix1[8]; /* same as [2][1] */

/* you CAN make a 2D array (matrix) as a double pointer */
int **matrix2 = malloc(sizeof(int *) * 3); /* 3 rows of pointers */
for(int i=0; i<3; i++) {
  matrix2[i] = malloc(sizeof(int) * 3); /* three columns per row */
}

So basically if you know the size of your matrix at compile time, then you're better off declaring it as such. I believe also starting at C99 or maybe C11 you can also have variable-length arrays and matrices, so that's nice, too. But doing anything more than 1 dimension starts to get tricky when dealing wth pure pointers. E.g.:

int matrix4d[6][4][3][8]; /* 4D matrix */

/* or... 4D matrix! */
int ****matrix4d1 = malloc(sizeof(int***) * 6);
for(int i=0; i<6; i++) {
  matrix4d1[i] = malloc(sizeof(int**) * 4);
  for(int j=0; j<4; j++) {
    matrix4d1[i][j] = malloc(sizeof(int*) * 3);
    for(int k=0; i<3; k++) {
      matrix4d1[i][j][k] = malloc(sizeof(int) * 8);
    }
  }
}

I hope that makes sense.

2

u/[deleted] 3d ago edited 3d ago

Pointers and arrays are functionally the same. Both of them point to the first element in the array. So either way, a pointer variable and an array variable point at the same thing.

However, declaring the variable as an array gets you access to C's array syntax (accessing elements with the subscript operator []). This makes the array much easier to interact with in a loop, since otherwise you would have to do the math for accessing individual elements yourself as an offset of the original pointer. Multidimensional arrays make this more complicated.

So all this is doing is making the code inside the loop a little easier to read.

Edit: This is not quite right so retracting, my bad!

2

u/ReallyEvilRob 3d ago

Right. I will just add that the post increment operator needs to know the size of the datatype the pointer is pointing to in order to increment the pointer to the correct address. A pointer to a pointer will only increment by 8 bytes on x86_64. That is different from what the row index needs to be incremented by. Since each row is 3 ints, the row address needs to be incremented by 12 bytes. Since the declaration specifies 3 ints per row, the row address is calculated correctly by the compiler.

2

u/Rabbitical 3d ago

But you can subscript a pointer? That's fundamental to C you don't need to explicitly define an array to do that. It's true of course you can't do it multi dimensionally without defining the column width first. But you certainly can access 'arr[5]' from an 'int* arr' parameter.

1

u/ReallyEvilRob 3d ago

Sure. You can apply the subscript operator to any pointer type. If you have int **a, then a[i][j] is legal. It might not be correct, though.

1

u/Conscious_Support176 3d ago edited 3d ago

That’s not quite true, or is a bit misleading shall we say.

Both int [][3] mat, and int [2][3] are syntactic sugar for int (*mat)[3], which is the pointer to first element that the array decays to.

All three will do the same and you would not need to change one line of the function definition.

The [4] is part of the type, which is required for the pointer arithmetic as you were saying.

1

u/Educational-Paper-75 3d ago

Can't see any.