#include <stdio.h>
struct BankAccount {
int ID;
float balance;
};
struct BankAccount mary; // Global struct variable
int main( int argc, char *argv[] )
{
struct BankAccount john; // Local struct variable
mary.balance = 900;
john.balance = 500;
printf("%f\n\n", mary.balance + john.balance);
}
|
Consider the following program with 2 struct BankAccount (local) variables:
#include <stdio.h>
struct BankAccount {
int ID;
float balance;
};
int main( int argc, char *argv[] )
{
struct BankAccount john, mary;
john.balance = 500;
mary.balance = 500;
printf("j: %f m:%f\n\n", john.balance, mary.balance);
}
|
How to define a pointer variable p to a struct BankAccount typed variable:
#include <stdio.h>
struct BankAccount {
int ID;
float balance;
};
int main( int argc, char *argv[] )
{
struct BankAccount john, mary, *p ;
// p can store addr of struct BankAccount vars
john.balance = 500;
mary.balance = 500;
printf("j: %f m:%f\n\n", john.balance, mary.balance);
}
|
&john and &mary are address value of struct BankAccount variables:
#include <stdio.h>
struct BankAccount {
int ID;
float balance;
};
int main( int argc, char *argv[] )
{
struct BankAccount john, mary, *p ;
// p can store addr of struct BankAccount vars
john.balance = 500;
&john
mary.balance = 500;
&mary
printf("j: %f m:%f\n\n", john.balance, mary.balance);
}
|
So we can assign &john and/or &mary to p:
#include <stdio.h>
struct BankAccount {
int ID;
float balance;
};
int main( int argc, char *argv[] )
{
struct BankAccount john, mary, *p ;
// p can store addr of struct BankAccount vars
john.balance = 500;
p = &john; // Now *p ≡ john
mary.balance = 500;
p = &mary; // Now *p ≡ mary
printf("j: %f m:%f\n\n", john.balance, mary.balance);
}
|
And we can use the expression (*p).balance to update their balance member variable:
#include <stdio.h>
struct BankAccount {
int ID;
float balance;
};
int main( int argc, char *argv[] )
{
struct BankAccount john, mary, *p ;
// p can store addr of struct BankAccount vars
john.balance = 500;
p = &john; // Now *p ≡ john
(*p).balance = (*p).balance + 2000;
mary.balance = 500;
p = &mary; // Now *p ≡ mary
(*p).balance = (*p).balance + 9000;
printf("j: %f m:%f\n\n", john.balance, mary.balance);
}
|
|