Home > Net >  append on c (pointers of pointers)
append on c (pointers of pointers)

Time:11-05

I just started learning C language, and I can't fully understand why we should use pointers of pointers in order to append an element into the table (*tab). here's the code :

#include "append.h"

int append(int ** tab, size_t *size, int value){
    int *nouveauTab = realloc(*tab, (*size   1) * sizeof(int));
    if (nouveauTab == NULL){
        return 0;
    }
    *tab = nouveauTab;
    (*tab)[*size] = value;
    (*size)  ;
    return 1;
}

CodePudding user response:

If not to use pointer to pointer then the pointer tab will be passed by value. That is the function will deal with a copy of the value of the original pointer. Changing the copy does not influence on the original pointer. It will stay unchanged because it is its copy that was changed within the function.

So you need to pass the pointer by reference.

In C passing by reference means passing an object (a pointer is an object) indirectly through a pointer to it. Thus dereferencing the pointer the function will have a direct access to the original object. In the case of your function to the original pointer like

*tab = nouveauTab;

CodePudding user response:

The short answer is: Because you want to change the value of a pointer in the caller of append. That happens here: *tab = nouveauTab;

The code calling your append function will look something like:

int* table = NULL;
size_t table_size = 0;
if (append(&table, &table_size, 42) == 0)
{
    puts("append failed");
}
else
{
    printf(size is now %zu and element %zu is %d", table_size, table_size-1, table[table_size-1]);
}

So your code expects that append (on success) will change the value of both table and table_size. That requires that you pass the function pointers to these two variables.

If you did it without usinb pointers, i.e. like:

if (append(table, table_size, 42) == 0)

the function would not be able to change their values as C would just pass a copy of their current values.

A simple example using int

void foo(int x)
{
    x = x   1;
    printf("%d\n", x);
}

int x = 42;
printf("%d\n", x);
foo(x);
printf("%d\n", x);

will print

42
43
42  <--- x not changed by `foo` because we passed the value of x (i.e. 42)

but with this:

void foo(int* x)
{
    *x = *x   1;
    printf("%d\n", *x);
}

int x = 42;
printf("%d\n", x);
foo(&x);
printf("%d\n", x);

it will print

42
43
43  <--- x was changed by `foo` because we passed a pointer
  • Related