cpointersstructpass-by-referencefunction-declaration

Is it possible to modify the content of a struct pointer inside a function?


I am C begginer, I was trying to create a function that modify the content of a struct pointer, but it couldn't make it, instead, the content remains the same.

Here my code:

#include <stdio.h>
#include <stdlib.h>

typedef struct
{
  int age;
  int code;
}person;

void enter(person *struct_pointer);

void main(void)
{
  person *person_1 = NULL;

  enter(person_1);
  printf("CODE: %i\n", person_1->code);
  free(person_1);
}

void enter(person *struct_pointer)
{
 struct_pointer = malloc(sizeof(*struct_pointer));
 struct_pointer->age = 10;
 struct_pointer->code = 5090;
}

In the example above when I print code of person_1 it does not print nothing, so I assume is because person_1 is still pointing to NULL.

Can someone pls explain how can I do this, and if it cannot be made why.

Thanks


Solution

  • To change an object (pointers are objects) in a function you need to pass it to the function by reference.

    In C passing by reference means passing an object indirectly through a pointer to it. Thus dereferencing the pointer the function has a direct access to the original object.

    So your function should be declared and defined the following way

    void enter(person **struct_pointer)
    {
        *struct_pointer = malloc(sizeof(**struct_pointer));
        if ( *struct_pointer )
        {
            ( *struct_pointer )->age = 10;
            ( *struct_pointer )->code = 5090;
        }
    }
    

    and called like

    enter( &person_1 );
    

    Otherwise in case of this function declaration

    void enter(person *struct_pointer);
    

    the function will deal with a copy of the value of the passed pointer and changing the copy within the function will not influence on the original pointer.

    Pay attention to that according to the C Standard the function main without parameters shall be declared like

    int main( void )