C Programming language

Structure and sizeof function
Previous Home Next

Shorthand structure with typedef keyword

To make your source code more concise, you can use typedef keyword to create a synonym for a structure. This is an example of using typedef keyword to define address structure so when you want to create an instance of it you can omit the keyword struct.

1. typedef struct{
2. unsigned int house_number;
3. char street_name[50];
4. int zip_code;
5. char country[50]; 
6. } address;
7. address billing_addr;
8. address shipping_addr;

Copy a structure into another structure

One of major advantage of structure is you can copy it with = operator. The syntax as follows:

1. struct_intance1 = struct_intance2 

 

be noted that some old C compilers may not supports structure assignment so you have to assign each member variables one by one.

Structure and sizeof function

sizeof is used to get the size of any data types even with any structures. For example:

#include <stdio.h> 

typedef struct __address{ 

int house_number;// 4 bytes 

char street[50]; // 50 bytes

int zip_code; // 4 bytes

char country[20];// 20 bytes 

} address;//78 bytes in total 

 void main() 

{ 

// it returns 80 bytes 

printf("size of address is %d bytes\n",sizeof(address)); 

} 
Previous Home Next