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
CodePudding user response:
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 )
CodePudding user response:
You can modify the contents of the struct. It doesn't work for you because you are creating a new struct in the enter
function rather than editing the original. Just remove the first line (the one with malloc
) and instead allocate the struct in the declaration of the person_1
variable.