0% found this document useful (0 votes)
356 views

Structure in C

The document discusses C structures, including: 1) Defining a structure with the struct keyword to group related data types under a single name. For example, defining an "address" structure to hold house number, street name, zip code, country. 2) Declaring structure variables after a structure is defined to allocate memory for instances of the structure. 3) Accessing structure members using the dot operator, such as address.country to access the country field. 4) Common uses of structures like initializing, nesting other structures, and using pointers to structures.

Uploaded by

Anurag Sarkar
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
356 views

Structure in C

The document discusses C structures, including: 1) Defining a structure with the struct keyword to group related data types under a single name. For example, defining an "address" structure to hold house number, street name, zip code, country. 2) Declaring structure variables after a structure is defined to allocate memory for instances of the structure. 3) Accessing structure members using the dot operator, such as address.country to access the country field. 4) Common uses of structures like initializing, nesting other structures, and using pointers to structures.

Uploaded by

Anurag Sarkar
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

C Programming Language C Structure

C Structure
Introducing to C structure
In some programming contexts, you need to access multiple data types under a single name for easy manipulation; for example you want to refer to address with multiple data like house number, street, zip code, country C supports structure which allows you to wrap one or more variables with different data types. A structure can contain any valid data types like int, char, float even arrays and other structures. Each variable in structure is called a structure member.

Defining structure
To define a structure, you can use struct keyword. Here is the common syntax of structure definition: struct struct_name{ structure_member }; The name of structure is followed the rule of variable name. Here is an example of defining address structure: view source print?
1.struct address{ 2. unsigned int house_number; 3. char street_name[50]; 4. int zip_code; 5. char country[50]; 6. };

It contains house number as an positive integer, street name as a string, zip code as an integer and country as a string.

Declaring structure
The above example only defines an address structure without create any instance of it. To create or declare a structure you have two ways: The first way is declare a structure follows by structure definition like this : view source print?
1.struct struct_name { 2. structure_member;

3. 4.

... } instance_1,instance_2 instance_n;

In the second way you can declare your structure instance at a different location in your source code after structure definition. Here is structure declaration syntax : view source print?
1.struct struct_name instance_1,instance_2 instance_n;

Complex structure
Structure can contains arrays or other structures so it is sometimes called complex structure. For example address structure is a complex structure. We can define a complex structure which contains address structure as follows: view source print?
1.struct customer{ 2. char name[50]; 3. structure address billing_addr; 4. structure address shipping_addr; 5. };

Accessing structure member


To access structure members we can use dot operator (.) between structure name and structure member name as follows: structure_name.structure_member For example to access street name of structure address we do as follows: view source print?
1.struct address billing_addr; 2.billing_addr.country = "US";

If the structure contains another structure, we can use dot operator to access nested structure and use dot operator again to access variables of nested structure. view source print?
1.struct customer jack; 2.jack.billing_addr.country = "US";

Initializing structure
C programming language treats a structure as a custom data type therefore you can initialize a structure like a variable. Here is an example of initialize product structure: view source

print?
1.struct product{ 2. char name[50]; 3. double price; 4. } book = { "C programming language",40.5};

In above example, we define product structure, then we declare and initialize book structure with its name and price.

Structure and pointer


A structure can contain pointers as structure members and we can create a pointer to a structure as follows: view source print?
1.struct invoice{ 2. char* code; 3. char date[20]; 4. }; 5. 6. struct address billing_addr; 7. struct address *pa = &billing_addr;

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 view source print?
01.typedef struct{ 02. unsigned int house_number; 03. char street_name[50]; 04. int zip_code; 05. char country[50]; 06. } address; 07. 08. address billing_addr; 09. 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 view source print?

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. Let's take a look at simple program: view source print?
01.#include <stdio.h> 02. 03.typedef struct __address{ 04. int house_number;// 4 bytes 05. char street[50]; // 50 bytes 06. int zip_code; // 4 bytes 07. char country[20];// 20 bytes 08. 09.} address;//78 bytes in total 10. 11.void main() 12.{ 13. // it returns 80 bytes 14. printf("size of address is %d bytes\n",sizeof(address)); 15.}

You will never get the size of a structure exactly as you think it must be. The sizeof function returns the size of structure larger than it is because the compiler pads struct members so that each one can be accessed faster without delays. So you should be careful when you read the whole structure from file which were written from other programs.

Source code example of using C structure


In this example, we will show you how to use structure to wrap student information and manipulate it by reading information to an array of student structure and print them on to console screen. view source print?
01.#include <stdio.h> 02. 03.typedef struct _student{ 04. char name[50]; 05. unsigned int mark; 06.} student; 07.

08. 09. 10.void print_list(student list[], int size); 11.void read_list(student list[], int size); 12. 13. 14. 15.void main(){ 16. 17. const int size = 3; 18. student list[size]; 19. 20. read_list(list,size); 21. 22. print_list(list,size); 23. 24. 25.} 26. 27.void read_list(student list[], int size) 28.{ 29. printf("Please enter the student information:\n"); 30. 31. for(int i = 0; i < size;i++){ 32. printf("\nname:"); 33. scanf("%S",&list[i].name); 34. 35. printf("\nmark:"); 36. scanf("%U",&list[i].mark); 37. } 38. 39.} 40. 41.void print_list(student list[], int size){ 42. printf("Students' information:\n"); 43. 44. for(int i = 0; i < size;i++){ 45. printf("\nname: %s, mark: %u",list[i].name,list[i].mark); 46. } 47.}

Here is program's output


Please enter the student information: name:Jack mark:5 name:Anna mark:7

name:Harry mark:8 Students' information: name: J, mark: 5 name: A, mark: 7 name: H, mark: 8

Structure Declarations

A "structure declaration" names a type and specifies a sequence of variable values (called "members" or "fields" of the structure) that can have different types. An optional identifier, called a "tag," gives the name of the structure type and can be used in subsequent references to the structure type. A variable of that structure type holds the entire sequence defined by that type. Structures in C are similar to the types known as "records" in other languages.

Syntax
struct-or-union-specifier:

struct-or-union identifier opt { struct-declaration-list } struct-or-union identifier


struct-or-union:

struct union
struct-declaration-list:

struct-declaration struct-declaration-list struct-declaration The structure content is defined to be


struct-declaration:

specifier-qualifier-list struct-declarator-list ;
specifier-qualifier-list:

type-specifier specifier-qualifier-list opt type-qualifier specifier-qualifier-list opt


struct-declarator-list:

struct-declarator struct-declarator-list , struct-declarator


struct-declarator:

declarator The declaration of a structure type does not set aside space for a structure. It is only a template for later declarations of structure variables. A previously defined identifier (tag) can be used to refer to a structure type defined elsewhere. In this case, struct-declaration-list cannot be repeated as long as the definition is visible. Declarations of pointers to structures and typedefs for structure types can use the structure tag before the structure type is defined. However, the structure definition must be encountered prior to any actual use of the size of the fields. This is an incomplete definition of the type and the type tag. For this definition to be completed, a type definition must appear later in the same scope. The struct-declaration-list specifies the types and names of the structure members. A structdeclaration-list argument contains one or more variable or bit-field declarations. Each variable declared in struct-declaration-list is defined as a member of the structure type. Variable declarations within struct-declaration-list have the same form as other variable declarations discussed in this section, except that the declarations cannot contain storage-class specifiers or initializers. The structure members can have any variable types except type void, an incomplete type, or a function type. A member cannot be declared to have the type of the structure in which it appears. However, a member can be declared as a pointer to the structure type in which it appears as long as the structure type has a tag. This allows you to create linked lists of structures. Structures follow the same scoping as other identifiers. Structure identifiers must be distinct from other structure, union, and enumeration tags with the same visibility. Each struct-declaration in a struct-declaration-list must be unique within the list. However, identifier names in a struct-declaration-list do not have to be distinct from ordinary variable names or from identifiers in other structure declaration lists. Nested structures can also be accessed as though they were declared at the file-scope level. For example, given this declaration:

struct a { int x; struct b { int y; } var2; } var1;

these declarations are both legal:


struct a var3; struct b var4;

Examples
These examples illustrate structure declarations:
struct employee /* Defines a structure variable named temp */ { char name[20]; int id; long class; } temp;

The employee structure has three members: name, id, and class. The name member is a 20element array, and id and class are simple members with int and long type, respectively. The identifier employee is the structure identifier.
struct employee student, faculty, staff;

This example defines three structure variables: student, faculty, and staff. Each structure has the same list of three members. The members are declared to have the structure type employee, defined in the previous example.
struct { float x, y; } complex; /* Defines an anonymous struct and a */ /* structure variable named complex */

The complex structure has two members with float type, x and y. The structure type has no tag and is therefore unnamed or anonymous.
struct sample /* Defines a structure named x */ { char c; float *pf; struct sample *next; } x;

The first two members of the structure are a char variable and a pointer to a float value. The third member, next, is declared as a pointer to the structure type being defined (sample). Anonymous structures can be useful when the tag named is not needed. This is the case when one declaration defines all structure instances. For example:
struct { int x; int y; } mystruct;

Embedded structures are often anonymous.


struct somestruct { struct /* Anonymous structure */ { int x, y; } point; int type; } w;

Microsoft Specific The compiler allows an unsized or zero-sized array as the last member of a structure. This can be useful if the size of a constant array differs when used in various situations. The declaration of such a structure looks like this: struct identifier{ set-of-declarations type array-name[ ];};

Unsized arrays can appear only as the last member of a structure. Structures containing unsized array declarations can be nested within other structures as long as no further members are declared in any enclosing structures. Arrays of such structures are not allowed. The sizeof operator, when applied to a variable of this type or to the type itself, assumes 0 for the size of the array. Structure declarations can also be specified without a declarator when they are members of another structure or union. The field names are promoted into the enclosing structure. For example, a nameless structure looks like this:
struct s { float y; struct { int a, b, c; }; char str[10]; } *p_s;

. . . p_s->b = 100;

/* A reference to a field in the s structure */

See Structure and Union Members for information about structure references. END Microsoft Specific

See Also

You might also like