C arrays allow you to define type of variables that can hold several data items of the same kind but structure is another user defined data type available in C programming, which allows you to combine data items of different kinds.
C Structure is also collection of different data types which are grouped together and each element in a structure is called member of c language programming.
If you want to access structure members and structure variable should be declared.
Many structure variables can be created for same structure and memory will be allocated for each separately in c language .
In c language structure is a best practice to initialize a structure to null while declaring, if we don’t assign any values to structure members.
simple different between variable , array and structure are a normal C variable can hold only one data of one data type at a time. An array can hold group of data of same data type. A structure can hold group of data of different data types.
To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than one member for your program. The format of the struct statement is this:
Syntax:
Structure tag_name { data type var_nm1; data type var_nm2; data type var_nm3; }; |
The structure tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. At the end of the structure’s definition, before the final semicolon, you can specify one or more structure variables but it is optional.
Accessing Structure Members :
To access any member of a structure, we use the member access operator (.). The member access operator is coded as a period between the structure variable name and the structure member that we wish to access. You would use struct keyword to define variables of structure type. Following is the example to explain usage of structure:
#include<stdio.h> #include<string.h>struct Books { char title[100]; int book_id; }; int main( ) /* book 2 specification */ /* print Book1 info */ /* print Book2 info */ return 0; |
output:
Book 1 title : C Programming
Book 1 book_id : 1001
Book 2 title : Java Programming
book 2 book_id : 1002
Structures as Function Arguments :
You can pass a structure as a function argument in very similar way as you pass any other variable or pointer. You would access structure variables in the similar way as you have accessed in the above example:
#include<stdio.h> #include<string.h>struct Books { char title[100]; int book_id; }; /* function declaration */ /* book 1 specification */ /* book 2 specification */ /* print Book1 info */ /* Print Book2 info */ return 0; |
output:
Book 1 title : C Programming
Book 1 book_id : 1001
Book 2 title : Java Programming
book 2 book_id : 1002
The post Structure In C Language appeared first on I'm Programmer.