Maker Pro
Maker Pro

How do you change structure

champ1

Jul 17, 2018
55
Joined
Jul 17, 2018
Messages
55
When I want to change int in function I pass pointer to int so int will change
Code:
#include<stdio.h>

void foo ( int *ptr )
{
    *ptr = 10;
}

int main ()
{
   int a = 1;
  
   foo (&a);
  
   printf("%d", a);
    return 0;
}

I am trying to understand how we change the structure in function

Code:
int main ()
{
   struct node * P = NULL;
  
   foo (&P);
   foo (P);
    return 0;
}

What we pass address of structure or value of structure to change structure ?
 

Harald Kapp

Moderator
Moderator
Nov 17, 2011
13,722
Joined
Nov 17, 2011
Messages
13,722
I think you need to re-read the chapter on pointers in your learning material.

In your code:
*P is a structure
therefore
P is a pointer to the structure
and
&P is the address of the pointer to the structure.

When I want to change int in function I pass pointer to int so int will change
You can do that but it makes the code intransparent: outside of the function you can't see that the function actually changes the value of the int. It is imho much better to declare the function like so:
Code:
int foo(int anynumber){
   ...
   newnumber = ...

   return(newnumber);
}

Then in the calling routine use
Code:
int main ()
{
   int a = 1;
   int b = 0;

   b = foo (a); // or a = foo(a), it you really want to change the value of a

   ...
Which makes it transparent and clear that the function foo() does someting with "a" and returns a new value "b".
 
Top