-1

While I have seen some threads on this, I fail to understand the meaning behind triple pointers, since it seems that it's possible to do the same without them.

void Reading(int *N, int ***M) {

printf("Input an integer N: \n");
scanf("%d", N);
*M = malloc(N * sizeof(int*)); 
int i;
for (i = 0; i < N; i++)
    *(*M+i) = malloc(N * sizeof(int));
printf("Input N*N integers that will form a matrix \n");
int i, j;
for (i = 0; i < *N; i++)
    for (j = 0; j < *N; j++)
        scanf("%d", &((*M)[i][j]));
}

This code makes **M a 2D array. If I take the malloc procedures and put them into main, the triple pointer isn't needed anymore. Could someone please explain why this is the case ?

Nangs
  • 33
  • 1
  • 1
  • 6
  • 2
    It's purpose is to allow the address of the double-pointer to change within a function without returning a value (it's a simulated pass by reference for a double-pointer). Becoming a *3-star programmer* in C is not a compliment. A better design would be to type `Reading` as `int **Reading(...)` and declare `M` within `Reading`, allocate, validate and then return `M` and assign to the double-pointer in the caller. – David C. Rankin Oct 17 '18 at 06:44

1 Answers1

0

If I take the malloc procedures and put them into main, the triple pointer isn't needed anymore.

There are two ways to pass a variable to a function: either by value or by reference. When you pass the reference of a variable, that allows you to modify it.

Example:

void fun(int a) {
   a = 42; // Does nothing
}

int b = 9;
fun(b);
// b is unchanged.

void fun(int *a) {
   *a = 42;
}

int b = 9;
fun(&b);
// b equals 42.

Your variable happens to be a of type int **, when you pass the address (reference) of this variable, this makes it a int ***.

Maxime Chéramy
  • 17,761
  • 8
  • 54
  • 75
  • Technically in C there is only *one way to pass a variable* and that is *by value*. You can simulate a reference by passing the *address of* (e.g. a pointer to) the variable. – David C. Rankin Oct 17 '18 at 07:10
  • I understand that. But let's say we remove the third pointer from M, put the mallocs in main and leave only the two for loops and a scanf in the Reading function. The **M is still going to return modified with only two asterisks right ? – Nangs Oct 17 '18 at 07:22