Credits

Thursday, February 26, 2009

Structures or Records

A structure is defined as a collection of variables that are referenced under a name. In Pascal, we call this a record. In C or C++, we call this a structure, and in Java, we call this object.

General syntax of structure in C or C++:

struct structure_tag_name{
type variable_name1;
:
:
type variable_nameN;
} structure_variables;

sample structure definition:

struct address{
char name[30];
char street[30];
char zip[4];
};

or

struct {
char name[30];
char street[30];
char zip[4];
} address_info;

The difference in the two can be possible but not the same declaration may miss both the structure name or variables.

to assign or access the structure element:

strcpy(address_info.zip,"9500");
printf("%s",address_info.zip);

on the screen, you will see:
9500

See the complete sample program:



[+/-] show/hide




#include stdio.h /*enclose this library in <> */

main()
{
struct my_info{
char name[30];
float height;
float weight;
};

strcpy(my_info.name,"Rosilie");
my_info.height=64.0;
my_info.weight=48.0;

printf("\nHello %s",my_info.name);
printf("\nYou are %f inches tall",my_info.height);
printf("\nYou weigh %s kilograms",my_info.weight);
getche();
}

What is the output of the code above?
Translate this in C++.

AddThis