TIP: Click on subject to list as thread! ANSI
echo: c_plusplus
to: RICK ARDING
from: KURT KUZBA
date: 1997-03-27 00:48:00
subject: struct passing

RA>   the right way to pass a structure to a subroutine.
ra>......
   You have to use the proper notation. Your example worked,
but copying the structure to another one and then back IS, as
you surmised, redundant. You can just pass the structure by
reference, or by pointer. If passing by pointer, you must use
the proper pointer dereferencing syntax of -> instead of ..
Incidentally, it is generally more useful in C++ to use
classes, as opposed to structures. Instead of passing the
struct to its controlling functions, you contain the struct
and its controlling code within the class. In this way,
wherever you pass the class, its controlling code goes also.
//   STRCTPAS.CPP   PUBLIC DOMAIN   by Kurt Kuzba.  (3/26/97)
//   A simple example of passing structures in C++
#include 
#include 
typedef struct
{
   int hits, health, strength, charisma, gold,
      spells, armor, weapon, shield;
   char name[32];
} PLAYER_DATA;
void init_player(PLAYER_DATA *p)
{
// NOTE: pointer dereferencing required. can modify object
   p->hits = 10;
   p->health = 10;
   p->strength = 10;
   p->charisma = 10;
   p->gold = 50;
   p->spells = 0;
   p->armor = 1;
   p->weapon = 1;
   p->shield = 1;
   strcpy(p->name, "Unknown");
}
void bless_player(PLAYER_DATA &p)
{
// NOTE: struct dereferencing required. can modify object
   p.hits = 100;
   p.health = 100;
   p.strength = 100;
   p.charisma = 100;
   p.gold = 500;
   p.spells = 1000;
   p.armor = 10;
   p.weapon = 10;
   p.shield = 10;
}
void show_player(PLAYER_DATA p)
{
// NOTE: struct dereferencing required. can not modify object
   cout << "\nHits ____ " << p.hits
        << "\nHealth __ " << p.health
        << "\nStrength  " << p.strength
        << "\nCharisma  " << p.charisma
        << "\nGold ____ " << p.gold
        << "\nSpells __ " << p.spells
        << "\nArmor ___ " << p.armor
        << "\nWeapon __ " << p.weapon
        << "\nShield __ " << p.shield
        << "\nName ____ " << p.name
        << endl;
}
int main(void)
{
   PLAYER_DATA plyr[5];
   init_player(&plyr[0]);     // NOTE: pointer data required
   show_player(plyr[0]);      // NOTE: struct data required
   bless_player(plyr[0]);     // NOTE: struct data required
   show_player(plyr[0]);      // NOTE: struct data required
   return 0;
}
> ] This Universe is 3-D captioned for the Magic Eye impaired...
---
---------------
* Origin: *YOPS ]I[* 3.1 GIG * RA/FD/FE RADist * Milwaukee, WI (1:154/750)

SOURCE: echomail via exec-pc

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.