C – Special Characters

Special Characters in C ”; Previous Next The C language identifies a character set that comprises English alphabets – upper and lowercase (A to Z as well as “a” to “z”), digits 0 to 9, and certain other symbols called “special characters” with a certain meaning attached to them. While many of the characters in the special symbol category are defined as operators, certain combinations of characters also have a special meaning attached to them. For example, “n” is known as the newline character. Such combinations are called escape sequences. In C language, quotation marks too have a special meaning. Double quotes are used for strings, while characters are enclosed inside single quotes. Read this chapter to learn more about the other special characters used in C programs. Parentheses () Parentheses are especially used to group one or more operands in an expression and control the order of operations in a statement. A part of the expression embedded inside parentheses has a higher order of precedence. Example int a = 2, b = 3, c = 4; int d = (a + b) * c; Braces { } Braces are especially used to define blocks of code, such as function bodies and loops. They are also used to initialize arrays and struct variables. Examples Braces in function definition − int add(int a, int b){ int sum = a + b; return sum; } Braces in array initialization − int arr[5] = {1, 2, 3, 4, 5}; Braces in struct variable − struct book { char title[10]; double price; int pages; }; struct book b1; struct book b1 = {“Learn C”, 675.50, 325}; Square Brackets [ ] Square brackets are used to declare arrays and access elements of an array with the subscript index. Example For example, to define an array of integers and access its third element, you would use square brackets − int arr[5] = {1, 2, 3, 4, 5}; int third = arr[2]; Asterisk (*) Apart from its use as a multiplication operator, the asterisk symbol (*) is also used to declare a pointer variable and dereference it to obtain the value of the target variable. Example For example, to define a pointer to an integer and access the value it points to, you would use an asterisk − int num = 10; int *ptr = # printf(“*d”, *ptr); Ampersand (&) The ampersand (&) symbol is used as the address-of operator. It returns the address of a variable. Example For example, to get the address of an integer variable, you would use an ampersand − int num = 10; int *ptr = # Comma (,) The comma is used as a separator between a statement or a function call. Example int a = 1, b = 2, c = 3; Semicolon (;) As a primary syntax rule in C, the semicolon indicates the end of a statement in a C program. Example printf(“Hello, world!”); Dot (.) The dot symbol (.) is used to access the members of a structure or a union. Example struct book b1 = {“Learn C”, 675.50, 325}; printf(“Title: %sn”, b1.title); printf(“Price: %lfn”, b1.price); printf(“No of Pages: %dn”, b1.pages); Arrow (→) The arrow symbol (→) is used to access the members of a structure or a union through a pointer. Example struct book b1 = {“Learn C”, 675.50, 325}; struct book *strptr; strptr = &b1; printf(“Title: %sn”, strptr->title); printf(“Price: %lfn”, strptr->price); printf(“No of Pages: %dn”, strptr->pages); Print Page Previous Next Advertisements ”;

C – Return Array from Function

Return array from function in C ”; Previous Next Functions in C help the programmers to adapt modular program design. A function can be defined to accept one or more than one arguments, it is able to return a single value to the calling environment. However, the function can be defined to return an array of values. In C, a function can be made to return an array by one of following methods − Passing the array as argument and returning the pointer Declaring a static array in a function and returning its pointer Using malloc() function Embedding the array inside a struct variable and passing it to a function We implement these methods to calculate the square, the cube and the square root of a given number. Pass array by reference In the following example, we declare an uninitialized array in main() and pass it to a function, along with an integer. Inside the function, the array is filled with the square, cube and square root. The function returns the pointer of this array, using which the values are access and printed in main() function. Example #include <stdio.h> #include <math.h> int arrfunction(int, float *); int main(){ int x=100; float arr[3]; arrfunction(x, arr); printf(“Square of %d: %fn”, x, arr[0]); printf(“cube of %d: %fn”, x, arr[1]); printf(“Square root of %d: %fn”, x, arr[2]); return 0; } int arrfunction(int x, float *arr){ arr[0]=pow(x,2); arr[1]=pow(x, 3); arr[2]=pow(x, 0.5); } Output Square of 100: 10000.000000 cube of 100: 1000000.000000 Square root of 100: 10.000000 Return static array Instead of passing an empty array from main(), we can declare an array inside the called function itself, fill it with the required values, and return its pointer. However, returning a pointer of a local variable is not acceptable, as it points to a variable that no longer exists. Note that a local variable ceases to exist as soon as the scope of the function is over. Hence, we need to use a static array inside the called function (arrfunction) and return its pointer back to main(). Example #include <stdio.h> #include <math.h> float * arrfunction(int); int main(){ int x=100, i; float *arr = arrfunction(x); printf(“Square of %d: %fn”, x, *arr); printf(“cube of %d: %fn”, x, arr[1]); printf(“Square root of %d: %fn”, x, arr[2]); return 0; } float *arrfunction(int x){ static float arr[3]; arr[0]=pow(x,2); arr[1]=pow(x, 3); arr[2]=pow(x, 0.5); return arr; } Output Square of 100: 10000.000000 cube of 100: 1000000.000000 Square root of 100: 10.000000 Now, consider the following function which will generate 10 random numbers and return them using an array and call this function as follows − Example #include <stdio.h> #include <time.h> #include <stdlib.h> /* function to generate and return random numbers */ int * getRandom( ) { static int r[10]; int i; /* set the seed */ srand( (unsigned)time( NULL ) ); for ( i = 0; i < 10; ++i) { r[i] = rand(); printf( “r[%d] = %dn”, i, r[i]); } return r; } /* main function to call above defined function */ int main () { /* a pointer to an int */ int *p; int i; p = getRandom(); for ( i = 0; i < 10; i++ ) { printf( “*(p + %d) : %dn”, i, *(p + i)); } return 0; } When the above code is compiled together and executed, it produces the following result − Output r[0] = 2110147662 r[1] = 1427553496 r[2] = 1243625529 r[3] = 857484361 r[4] = 513293736 r[5] = 964923407 r[6] = 36104419 r[7] = 1248464892 r[8] = 1838450240 r[9] = 2096489563 *(p + 0) : 2110147662 *(p + 1) : 1427553496 *(p + 2) : 1243625529 *(p + 3) : 857484361 *(p + 4) : 513293736 *(p + 5) : 964923407 *(p + 6) : 36104419 *(p + 7) : 1248464892 *(p + 8) : 1838450240 *(p + 9) : 2096489563 Using malloc() function The malloc() function is available as a library function in stdlib.h header file. It dynamically allocates a block of memory during the runtime of a program. Normal declaration of variables causes the memory to be allocated at the compile time. void *malloc(size_t size); The malloc() function returns a generic void pointer. To assign values of a certain data type in the allocated memory, it must be typecast to the required type. For example, to store an int data, it must be typecast to int * as follows − int *x = (int *)malloc(sizeof(int); Let us allocate a block of memory sufficient to store three float values corresponding to square, cube and square root of a number, and return the float pointer to main(), inside which the computed values are displayed. Example #include <stdio.h> #include <math.h> #include <stdlib.h> float * arrfunction(int); int main(){ int x=16, i; float *arr = arrfunction(x); printf(“Square of %d: %fn”, x, arr[0]); printf(“cube of %d: %fn”, x, arr[1]); printf(“Square root of %d: %fn”, x, arr[2]); return 0; } float *arrfunction(int x){ float *arr = (float *)malloc(3*sizeof(float)); arr[0]=pow(x,2); arr[1]=pow(x, 3); arr[2]=pow(x, 0.5); return arr; } Output Square of 16: 256.000000 cube of 16: 4096.000000 Square root of 16: 4.000000 Using array element in struct In this method, we will declare a struct, inside which there is an float array as its element. The called function (myfunction) declares a struct variable, populates the array element with square, cube and the square root of the argument received by it, and returns it to the main() function. Example #include <stdio.h> #include <math.h> struct mystruct{ float arr[3]; }; struct mystruct myfunction(int x); int main(){ int x = 9; struct mystruct s = myfunction(x); printf(“Square of %d: %fn”, x, s.arr[0]); printf(“cube of %d: %fn”, x, s.arr[1]); printf(“Square root of %d: %fn”,

C – Nested Structures

Nested Structures in C ”; Previous Next What is a Nested Structure in C? A structure within a structure is known as nested structure in C. When one of the elements in the definition of a struct type is of another struct type, then we call it a nested structure in C. Nested structures are defined when one of the elements of a struct type is itself a composite representation of one or more types. Nested Structure Declaration A nested structure can be declared by using a structure as a member of another structure. Syntax A general syntax of a nested structure is as follows − struct struct1{ type var1; type var2; struct struct2 strvar; } Example We can think of nested structures in the following situation. If we want to define a struct type representing a “student” with “name” and “age” as its elements and another struct type called “course” that is characterized by “course ID”, “title”, and “credit points”. Here, the “student” structure has an inner course structure. struct student{ char *name; int age; struct course c1; }; The “student” variable will be stored in the memory as follows − Name Age Course Kiran 25 001 C Programming 6 Accessing Members of a Nested Structure The structure”s members can be accessed by using the dot (.) operator. In the case of nested structures, there can be multiple levels of structures. So, you need to use the dot (.) operator for each level of the structure to access the members of the nested structure. Syntax Below is the syntax to access members of nested structure – level1.level2.member_name; Here, level1 represents the structure variable of the outer (parent) structure, and level2 represents the structure variable of the inner (child) structure. Example Consider the following nested structure definition – struct employee{ char name[10]; float salary; struct dob{ int d, m, y; } d1; }e1; Here, e1 is the structure variable of the outer (level 1) structure “employee” and d1 is the structure variable of the inner (level 2) structure “dob“. To access the members of the employee structure, use e1.member_name. printf(“Name: %sn”, e1.name); printf(“Salary: %fn”, e1.salary); To access the members of the dob structure, use e1.d1.member_name. printf(“Date of Birth: %d-%d-%dn”, e1.d1.d, e1.d1.m, e1.d1.y); The nesting of structures can be performed in two different ways − Defining an inline structure Including the element of a structure already defined Let us learn these methods using suitable examples. Nested Structure by Defining Inline Structure In this method, we shall define an “employee” data type with one of its elements being “date of birth”. C doesn’t have a built-in type for “date”. We shall declare the “dob” struct with three “int” types “d”, “m” and “y” inside the “employee” structure and its variable “d1” is one of the elements of the outer type. Example Take a look at the following example − #include <stdio.h> #include <string.h> struct employee{ char name[10]; float salary; struct dob{ int d, m, y; } d1; }; int main(){ struct employee e1 = {“Kiran”, 25000, {12, 5, 1990}}; printf(“Name: %sn”, e1.name); printf(“Salary: %fn”, e1.salary); printf(“Date of Birth: %d-%d-%dn”, e1.d1.d, e1.d1.m, e1.d1.y); return 0; } Output When you run this code, it will produce the following output − Name: Kiran Salary: 25000.000000 Date of Birth: 12-5-1990 You can see that the variable of “employee” type is initialized with its “date” element having another pair of curly brackets. Nested Structure by Defining Separate Structure The other approach for using nested structures is to define the inner struct type first, and then use its variable as one of the elements in the outer struct type, which is defined afterwards. Here, the “dob” type is defined in the beginning; it has three “int” elements − d, m and y. The “employee” struct type is defined afterwards. Example 1 Since “dob” is already defined, we can have an element of its type inside “employee”. #include <stdio.h> #include <string.h> struct dob{ int d, m, y; }; struct employee{ char name[10]; float salary; struct dob d1; }; int main(){ struct employee e1 = {“Kiran”, 25000, {12, 5, 1990}}; printf(“Name: %sn”, e1.name); printf(“Salary: %fn”, e1.salary); printf(“Date of Birth: %d-%d-%dn”, e1.d1.d, e1.d1.m, e1.d1.y); return 0; } Output Run the code and check its output − Name: Kiran Salary: 25000.000000 Date of Birth: 12-5-1990 Note that the inner struct type should be defined before the outer type. We can also declare a variable of “dob” type and then include it in the initialization of “employee” type variable, as shown below − struct dob d1 = {12, 5, 1990}; struct employee e1 = {“Kiran”, 25000, d1}; Example 2 In the following code, the nesting of structure goes upto two levels. In other words, the outer struct type “employee” has one element that is a variable of experience struct type. In turn, the experience structure has two elements of another struct type called “date”. Hence, the memory allocation for “employee” variable can be understood with the following illustration − Name Salary Designation from to Kiran 25000 Clerk 12 5 1990 31 3 2021 Here is the complete code − #include <stdio.h> #include <string.h> struct date{ int d, m, y; }; struct experience{ char designation[10]; struct date from; struct date to; }; struct employee{ char name[10]; float salary; struct experience exp;

C – File I/O (File Handling)

File Handling in C ”; Previous Next File Handling in C File handling in C is the process of handling file operations such as creating, opening, writing data, reading data, renaming, and deleting using the C language functions. With the help of these functions, we can perform file operations to store and retrieve the data in/from the file in our program. Need of File Handling in C If we perform input and output operations using the C program, the data exists as long as the program is running, when the program is terminated, we cannot use that data again. File handling is required to work with files stored in the external memory i.e., to store and access the information to/from the computer”s external memory. You can keep the data permanently using file handling. Types of Files A file represents a sequence of bytes. There are two types of files: text files and binary files − Text file − A text file contains data in the form of ASCII characters and is generally used to store a stream of characters. Each line in a text file ends with a new line character (“n”), and generally has a “.txt” extension. Binary file − A binary file contains data in raw bits (0 and 1). Different application programs have different ways to represent bits and bytes and use different file formats. The image files (.png, .jpg), the executable files (.exe, .com), etc. are the examples of binary files. FILE Pointer (File*) While working with file handling, you need a file pointer to store the reference of the FILE structure returned by the fopen() function. The file pointer is required for all file-handling operations. The fopen() function returns a pointer of the FILE type. FILE is a predefined struct type in stdio.h and contains attributes such as the file descriptor, size, and position, etc. typedef struct { int fd; /* File descriptor */ unsigned char *buf; /* Buffer */ size_t size; /* Size of the file */ size_t pos; /* Current position in the file */ } FILE; Declaring a File Pointer (FILE*) Below is the syntax to declare a file pointer − FILE* file_pointer; Opening (Creating) a File A file must be opened to perform any operation. The fopen() function is used to create a new file or open an existing file. You need to specify the mode in which you want to open. There are various file opening modes explained below, any one of them can be used during creating/opening a file. The fopen() function returns a FILE pointer which will be used for other operations such as reading, writing, and closing the files. Syntax Below is the syntax to open a file − FILE *fopen(const char *filename, const char *mode); Here, filename is the name of the file to be opened, and mode defines the file”s opening mode. File Opening Modes The file access modes by default open the file in the text or ASCII mode. If you are going to handle binary files, then you will use the following access modes instead of the above-mentioned ones: “rb”, “wb”, “ab”, “rb+”, “r+b”, “wb+”, “w+b”, “ab+”, “a+b” There are various modes in which a file can be opened. The following are the different file opening modes − Mode Description r Opens an existing text file for reading purposes. w Opens a text file for writing. If it does not exist, then a new file is created. Here your program will start writing content from the beginning of the file. a Opens a text file for writing in appending mode. If it does not exist, then a new file is created. Here your program will start appending content in the existing file content. r+ Opens a text file for both reading and writing. Opens a text file for both reading and writing. It first truncates the file to zero length if it exists, otherwise creates a file if it does not exist. a+ Opens a text file for both reading and writing. It creates the file if it does not exist. The reading will start from the beginning but writing can only be appended. Example of Creating a File In the following example, we are creating a new file. The file mode to create a new file will be “w” (write-mode). #include <stdio.h> int main() { FILE * file; // Creating a file file = fopen(“file1.txt”, “w”); // Checking whether file is // created or not if (file == NULL) { printf(“Error in creating file”); return 1; } printf(“File created.”); return 0; } Output File created. Example of Opening a File In the following example, we are opening an existing file. The file mode to open an existing file will be “r” (read-only). You may also use other file opening mode options explained above. Note: There must be a file to be opened. #include <stdio.h> int main() { FILE * file; // Opening a file file = fopen(“file1.txt”, “r”); // Checking whether file is // opened or not if (file == NULL) { printf(“Error in opening file”); return 1; } printf(“File opened.”); return 0; } Output File opened. Closing a File Each file must be closed after performing operations on it. The fclose() function closes an opened file. Syntax Below is the syntax of fclose() function − int fclose(FILE *fp); The fclose() function returns zero on

C – Bit Fields

Bit Fields in C ”; Previous Next When we declare a struct or a union type, the size of the struct/union type variable depends on the individual size of its elements. Instead of the default memory size, you can set the size the bits to restrict the size. The specified size is called bit fields. This is the syntax you would use to declare a bit field − struct { data_type elem : width; }; Let”s suppose your C program contains a number of TRUE/FALSE variables grouped in a structure called status, as follows − struct { unsigned int widthValidated; unsigned int heightValidated; } status; This structure requires 8 bytes of memory space but in actual, we are going to store either “0” or “1” in each of the variables. The C programming language offers a better way to utilize the memory space in such situations. If you are using such variables inside a structure, then you can define the width of the variables which tells the C compiler that you are going to use only those many number of bytes. For example, the above structure can be re-written as follows − struct { unsigned int widthValidated : 1; unsigned int heightValidated : 1; } status; The above structure requires 4 bytes of memory space for the status variable, but only 2 bits will be used to store the values. Example If you will use up to 32 variables, each one with a width of 1 bit, then also the status structure will use 4 bytes. However, as soon as you have 33 variables, it will allocate the next slot of the memory and it will start using 8 bytes. Let us check the following example to understand the concept − #include <stdio.h> /* define simple structure */ struct { unsigned int widthValidated; unsigned int heightValidated; } status1; /* define a structure with bit fields */ struct { unsigned int widthValidated : 1; unsigned int heightValidated : 1; } status2; int main() { printf(“Memory size occupied by status1: %dn”, sizeof(status1)); printf(“Memory size occupied by status2: %dn”, sizeof(status2)); return 0; } Output When the above code is compiled and executed, it produces the following Output − Memory size occupied by status1: 8 Memory size occupied by status2: 4 Bit Field Declaration The declaration of a bit-field has the following form inside a structure − struct { type [member_name] : width ; }; The following table describes the variable elements of a bit field − Element Description type An integer type that determines how a bit-field”s value is interpreted. The type may be int, signed int, or unsigned int. member_name The name of the bit-field. width Number of bits in the bit-field. “width” must be less than or equal to bit width of specified type. The variables defined with a predefined width are called bit fields. A bit field can hold more than a single bit; for example, if you need a variable to store a value from 0 to 7, then you can define a bit field with a width of 3 bits, as follows − struct { unsigned int age : 3; } Age; The above structure definition instructs the C compiler that the variable “Age” is going to use only 3 bits to store the value. If you try to use more than 3 bits, then it will not allow you to do so. Example Let us try the following example − #include <stdio.h> struct { unsigned int age : 3; } Age; int main() { Age.age = 4; printf(“Sizeof(Age): %dn”, sizeof(Age)); printf(“Age.age: %dn”, Age.age); Age.age = 7; printf(“Age.age : %dn”, Age.age); Age.age = 8; printf(“Age.age : %dn”, Age.age); return 0; } Output When the above code is compiled, it will compile with a warning − warning: unsigned conversion from ”int” to ”unsigned char:3” changes value from ”8” to ”0” [-Woverflow]| And, when executed, it will produce the following output − Sizeof(Age): 4 Age.age: 4 Age.age: 7 Age.age: 0 You can use Bit Fields in situations where the available storage is limited. Bit Fields also prove efficient when devices transmit status or information encoded into multiple bits. Whenever certain encryption programs need to access the bits within a byte, bit fields are used to define the data structure. Print Page Previous Next Advertisements ”;

C – Arrays of Structures

Array of Structures in C ”; Previous Next In C programming, the struct keyword is used to define a derived data type. Once defined, you can declare an array of struct variables, just like an array of int, float or char types is declared. An array of structures has a number of use-cases such as in storing records similar to a database table where you have each row with different data types. Usually, a struct type is defined at the beginning of the code so that its type can be used inside any of the functions. You can declare an array of structures and later on fill data in it or you can initialize it at the time of declaration itself. Initializing a Struct Array Let us define a struct type called book as follows − struct book{ char title[10]; double price; int pages; }; During the program, you can declare an array and initialize it by giving the values of each element inside curly brackets. Each element in the struct array is a struct value itself. Hence, we have the nested curly brackets as shown below − struct book b[3] = { {“Learn C”, 650.50, 325}, {“C Pointers”, 175, 225}, {“C Pearls”, 250, 250} }; How does the compiler allocate memory for this array? Since we have an array of three elements, of struct whose size is 32 bytes, the array occupies “32 x 3” bytes. Each block of 32 bytes will accommodate a “title”, “price” and “pages” element. L E A R N C 675.50 325 C P O I N T E R S 175 225 C P E A R L S 250 250 Declaring a Struct Array You can also declare an empty struct array. Afterwards, you can either read the data in it with scanf() statements or assign value to each element as shown below − struct book b[3]; strcpy(b[0].title, “Learn C”); b[0].price = 650.50; b[0].pages=325; strcpy(b[1].title, “C Pointers”); b[1].price = 175; b[1].pages=225; strcpy(b[2].title, “C Pearls”); b[2].price = 250;250 b[2].pages=325; Reading a Struct Array We can also accept data from the user to fill the array. Example 1 In the following code, a for loop is used to accept inputs for the “title”, “price” and “pages” elements of each struct element of the array. #include <stdio.h> struct book{ char title[10]; double price; int pages; }; int main(){ struct book b[3]; strcpy(b[0].title, “Learn C”); b[0].price = 650.50; b[0].pages = 325; strcpy(b[1].title, “C Pointers”); b[1].price = 175; b[1].pages = 225; strcpy(b[2].title, “C Pearls”); b[2].price = 250; b[2].pages = 325; printf(“nList of Books:n”); for (int i = 0; i < 3; i++){ printf(“Title: %s tPrice: %7.2lf tPages: %dn”, b[i].title, b[i].price, b[i].pages); } return 0; } Output When you run this code, it will produce the following output − List of Books: Title: Learn C Price: 650.50 Pages: 325 Title: C Pointers Price: 175.00 Pages: 225 Title: C Pearls Price: 250.00 Pages: 325 Example 2 In this example, a struct type called student is defined. Its elements are “name”; marks in physics, chemistry and maths; and the “percentage”. An array of three struct student types is declared and the first four elements are populated by user input, with a for loop. Inside the loop itself, the “percent” element of each subscript is computed. Finally, an array of students with their names, marks and percentage is printed to show the marklist. #include <stdio.h> struct student{ char name[10]; int physics, chemistry, maths; double percent; }; int main(){ struct student s[3]; strcpy(s[0].name, “Ravi”); s[0].physics = 50; s[0].chemistry = 60; s[0].maths = 70; strcpy(s[1].name, “Kiran”); s[1].physics = 55; s[1].chemistry = 66; s[1].maths = 77; strcpy(s[2].name, “Anil”); s[2].physics = 45; s[2].chemistry = 55; s[2].maths = 65; for (int i = 0; i < 3; i++){ s[i].percent = (double)(s[i].physics + s[i].maths + s[i].chemistry)/3; } printf(“nNametPhysicstChemistrytMathstPercentn”); for(int i = 0; i < 3; i++){ printf(“%s tt%d tt%d tt%d tt%5.2lfn”, s[i].name, s[i].physics, s[i].chemistry, s[i].maths, s[i].percent); } return 0; } Output When you run this code, it will produce the following output − Name Physics Chemistry Maths Percent Ravi 50 60 70 60.00 Kiran 55 66 77 66.00 Anil 45 55 65 55.00 Sorting a Struct Array Let us take another example of struct array. Here, we will have the array of “book” struct type sorted in ascending order of the price by implementing bubble sort technique. Note: The elements of one struct variable can be directly assigned to another struct variable by using the assignment operator. Example Take a look at the example − #include <stdio.h> struct book{ char title[15]; double price; int pages; }; int main(){ struct book b[3] = { {“Learn C”, 650.50, 325}, {“C Pointers”, 175, 225}, {“C Pearls”, 250, 250} }; int i, j; struct book temp; for(i = 0; i < 2; i++){ for(j = i; j < 3; j++){ if (b[i].price > b[j].price){ temp = b[i]; b[i] = b[j]; b[j] = temp; } } } printf(“nList of Books in Ascending Order of Price:n”); for (i = 0; i < 3; i++){ printf(“Title: %s tPrice: %7.2lf tPages: %dn”, b[i].title, b[i].price, b[i].pages); } return 0; } Output When you run this code, it will produce the following output − List of Books in Ascending Order of Price: Title: C Pointers Price: 175.00 Pages: 225

C – Unions

Unions in C ”; Previous Next Unions in C A union is a special data type available in C that allows to store different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multiple purpose. All the members of a union share the same memory location. Therefore, if we need to use the same memory location for two or more members, then union is the best data type for that. The largest union member defines the size of the union. Defining a Union Union variables are created in same manner as structure variables. The keyword union is used to define unions in C language. Syntax Here is the syntax to define a union in C language − union [union tag]{ member definition; member definition; … member definition; } [one or more union variables]; The “union 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 union”s definition, before the final semicolon, you can specify one or more union variables. Accessing the Union Members To access any member of a union, we use the member access operator (.). The member access operator is coded as a period between the union variable name and the union member that we wish to access. You would use the keyword union to define variables of union type. Syntax Here is the syntax to access the members of a union in C language − union_name.member_name; Initialization of Union Members You can initialize the members of the union by assigning the value to them using the assignment (=) operator. Syntax Here is the syntax to initialize members of union − union_variable.member_name = value; Example The following code statement shows to initialization of the member “i” of union “data” − data.i = 10; Examples of Union Example 1 The following example shows how to use unions in a program − #include <stdio.h> #include <string.h> union Data{ int i; float f; char str[20]; }; int main(){ union Data data; data.i = 10; data.f = 220.5; strcpy(data.str, “C Programming”); printf(“data.i: %d n”, data.i); printf(“data.f: %f n”, data.f); printf(“data.str: %s n”, data.str); return 0; } Output When the above code is compiled and executed, it produces the following result − data.i: 1917853763 data.f: 4122360580327794860452759994368.000000 data.str: C Programming Here, we can see that the values of i and f (members of the union) show garbage values because the final value assigned to the variable has occupied the memory location and this is the reason that the value of str member is getting printed very well. Example 2 Now let”s look at the same example once again where we will use one variable at a time which is the main purpose of having unions − #include <stdio.h> #include <string.h> union Data{ int i; float f; char str[20]; }; int main(){ union Data data; data.i = 10; printf(“data.i: %d n”, data.i); data.f = 220.5; printf(“data.f: %f n”, data.f); strcpy(data.str, “C Programming”); printf(“data.str: %s n”, data.str); return 0; } Output When the above code is compiled and executed, it produces the following result − data.i: 10 data.f: 220.500000 data.str: C Programming Here, the values of all the Union members are getting printed very well because one member is being used at a time. Size of a Union The size of a union is the size of its largest member. For example, if a union contains two members of char and int types. In that case, the size of the union will be the size of int because int is the largest member. You can use the sizeof() operator to get the size of a union. Example In the following example, we are printing the size of a union − #include <stdio.h> // Define a union union Data { int a; float b; char c[20]; }; int main() { union Data data; // Printing the size of the each member of union printf(“Size of a: %lu bytesn”, sizeof(data.a)); printf(“Size of b: %lu bytesn”, sizeof(data.b)); printf(“Size of c: %lu bytesn”, sizeof(data.c)); // Printing the size of the union printf(“Size of union: %lu bytesn”, sizeof(data)); return 0; } Output When you compile and execute the code, it will produce the following output − Size of a: 4 bytes Size of b: 4 bytes Size of c: 20 bytes Size of union: 20 bytes Difference between Structure and Union Both structures and unions are composite data types in C programming. The most significant difference between a structure and a union is the way they store their data. A structure stores each member in separate memory locations, whereas a union stores all its members in the same memory location. Here is a definition of union type called myunion − union myunion{ int a; double b; char c; }; The definition of a union is similar to the definition of a structure. A definition of “struct type mystruct” with the same elements looks like this − struct mystruct{ int a; double b; char c; }; The main difference between a struct and a union is the size of the variables. The compiler allocates the memory to a struct variable, to be able to store the values for all the elements. In mystruct, there are three elements

C – Dereference Pointer

Dereference Pointer in C ”; Previous Next Dereference Pointer in C The dereference operator is used to access and manipulate the value stored in the variable pointed by the pointer. The dereference or indirection operator (*) acts as a unary operator, and it needs a pointer variable as its operand. Syntax Below is the syntax to dereference a pointer − *pointer_variable; With the help of the above syntax (dereference pointer), you can get and update the value of any variable that is pointing by the pointer. How to Dereference a Pointer? To dereference a pointer, you need to follow the below-given steps: Create a variable and declare a pointer variable. Initialize the pointer by assigning the address of the variable. Now, you can dereference the pointer to get or update the value of the variable. Example In this example, we are demonstrating these three steps to deference a pointer − #include <stdio.h> int main() { // Create a variable and pointer variable int x = 10; int *ptr; // Initialize the pointer by assigning // the address of the variable ptr = &x; // Dereference the pointer printf(“Value of x = %dn”, *ptr); return 0; } Output Run the code and check its output − Value of x = 10 What is Dereferencing? The term “dereferencing” refers to accessing the value that is stored in the memory address referred by the pointer. The dereference operator (also called indirection operator) fetches the value of the target variable. Example In the above example, if we print “*b“, you get the value of “a“, i.e., 10. Similarly, printing “*y” displays 10.5. #include <stdio.h> int main (){ int a = 10; int *b = &a; float x = 10.5; float *y = &x; printf (“Address of ”a”: %d Value of ”a”: %dn”, b, *b); printf (“Address of ”x”: %d Value of ”x”: %fn”, y, *y); return 0; } Output Run the code and check its output − Address of ”a”: 6422028 Value of ”a”: 10 Address of ”x”: 6422024 Value of ”x”: 10.500000 Manipulating Value by Dereferencing Pointer The dereference operator also helps in indirectly manipulating the value of a variable referred to by a pointer. Example In this example, we change the value of “a” and “x” with the help of the dereference pointer − #include <stdio.h> int main (){ int a = 10; int *b = &a; float x = 10.5; float *y = &x; *b = 100; *y = 100.50; printf (“Address of ”a”: %d Value of ”a”: %dn”, b, *b); printf (“Address of ”x”: %d Value of ”x”: %fn”, y, *y); return 0; } Output Run the code and check its output − Address of ”a”: 6422028 Value of ”a”: 100 Address of ”x”: 6422024 Value of ”x”: 100.500000 Dereferencing a Double Pointer Just as you store the address of a normal variable in its pointer, you can have a pointer that stores the address of another pointer as well. A pointer having address of another pointer is known as double pointer or pointer-to-pointer. Let us declare a pointer to integer type and store the address of an integer variable in it. int a = 10; int *b = &a; The dereference operator fetches the value via the pointer − printf(“a: %d n Pointer to ”a” is ”b”: %d n Value at ”b”: %d”, a, b, *b); The value of integer variable, its address, and the value obtained by the dereference pointer will be printed as − a: 10 Pointer to ”a” is ”b”: 6422036 Value at ”b”: 10 Let us now declare a pointer that can store the address of “b”, which itself is a pointer to the integer type written as “int *”. Let”s assume that the compiler also allocates it the address 3000. Hence, “c” is a pointer to a pointer to int and should be declared as “int **“. int **c = &b; printf(“b: %d n Pointer to ”b” is ”c”: %d n Value at ”b”: %dn”, b, c, *c); You get the value of b (which is the address of a), the value of c (which is the address of b), and the dereferenced value from c (which is the address of a) b: 6422036 Pointer to ”b” is ”c”: 6422024 Value at ”b”: 6422036 Since “c” is a double pointer here, the first asterisk in its declaration points to “b” and the second asterisk in turn points to “a“. We can use the double reference pointer to obtain the value of “a” from “c“. printf(“Value of ”a” from ”c”: %d”, **c); This should display the value of a as 10. Example Try out the complete code given below − #include <stdio.h> int main (){ int a = 10; int *b = &a; printf(“a: %d n Address: %d n Value at ”a”: %dnn”, a, b, *b); int **c = &b; printf(“b: %d n Pointer to ”b” is ”c”: %d n Value at ”b”: %dn”, b, c, *c); printf(“Value of ”a” from ”c”: %d”, **c); return 0; } Output When you run this code, it will produce the following output − a: 10 Address: 6422036 Value at a: 10 b: 6422036 Pointer to ”b” is ”c”: 6422024 Value at ”b”: 6422036 Value of ”a” from ”c”: 10 Dereferencing a Structure Pointer The keyword “struct” is used to create a derived data type that consists of one or more elements of

C – Static Keyword

Static Keyword in C ”; Previous Next What is static Keyword in C? The static keyword in C is one of the storage class specifiers which has different meanings based on the context in which it is used. The “static” keyword is used to declare a static variable as well as to define a static function. When declared as “static”, a variable represents a static storage class. A static function is available only inside the program file (with “.c” extension) in which it is defined. One cannot use the “extern” keyword to import a static function into another file. Uses of static Keyword The following are the different uses of the static keyword Static Local Variable: When a local variable is declared with the static keyword, its lifetime will be till the end of the program and it retains the value between the function calls. Static Global Variable: When a global variable is declared with the static keyword, it can only be accessed within the same file. It is useful when you want to make a global variable as a private global variable to the file in which it is declared. Static Functions: When you function is declared as a static function, its scope will be limited to the file in which the function is declared. You cannot access the function in other files. Static Variables (static Keyword with Variables) When a variable is declared as static, it is initialized only once. The compiler persists with the variable till the end of the program. A static variable is also used to store data that should be shared between multiple functions. Here are some of the important points to note regarding a static variable − The compiler allocates space to the static variable in computer’s main memory. Unlike auto, a static variable is initialized to zero and not garbage. A static variable is not re-initialized on every function call, if it is declared inside a function. A static variable has local scope. Example of static Keyword with Variables In the following example, the variable “x” in the counter() function is declared as static. It is initialized to “0” when the counter() function is called for the first time. On each subsequent call, it is not re-initialized; instead it retains the earlier value. #include <stdio.h> int counter(); int main() { counter(); counter(); counter(); return 0; } int counter() { static int x; printf(“Value of x as it enters the function: %dn”, x); x++; printf(“Incremented value of x: %dn”, x); } Output When you run this code, it will produce the following output − Value of x as it enters the function: 0 Incremented value of x: 1 Value of x as it enters the function: 1 Incremented value of x: 2 Value of x as it enters the function: 2 Incremented value of x: 3 A static variable is similar to a global variable, as both of them, are initialized to 0 (for numeric types) or null pointers (for pointers) unless explicitly assigned. However, the scope of the static variable is restricted to the function or block in which it is declared. Static Functions (static Keyword with Functions) By default, every function is treated as global function by the compiler. They can be accessed anywhere inside a program. When prefixed with the keyword “static” in the definition, we get a static function that has a scope limited to its object file (the compiled version of a program saved with “.c” extension). This means that the static function is only visible in its object file. A static function can be declared by placing the keyword “static” before the function name. Example of static Keyword with Function (in Multiple Files) Open a console application with the CodeBlocks IDE. Add two files “file1.c” and “main.c”. The contents of these files are given as follows − Contents of “file1.c” − static void staticFunc(void) { printf(“Inside the static function staticFunc() “); } Contents of “main.c” − #include <stdio.h> #include <stdlib.h> int main() { staticFunc(); return 0; } Now, if the above console application project is built, then we will get an error, i.e., “undefined reference to staticFunc()”. This happens as the function staticFunc() is a static function and it is only visible in its object file. Example of static Keyword with Function (in the Same File) The following program demonstrates how static functions work in a C program − #include <stdio.h> static void staticFunc(void){ printf(“Inside the static function staticFunc() “); } int main(){ staticFunc(); return 0; } Output The output of the above program is as follows − Inside the static function staticFunc() In the above program, the function staticFunc() is a static function that prints “Inside the static function staticFunc()”. The main() function calls staticFunc(). This program works correctly as the static function is called only from its own object file. Example of static Keyword with Multiple Functions You can have multiple static functions in the same object file, as illustrated in the following example − #include <stdio.h> #include <stdlib.h> #include <math.h> // define the static function static int square( int num){ return num * num; } static void voidfn(){ printf (“From inside the static function.n”); } static int intfn(int num2){ return sqrt(num2); } int main(){ int n1, val; n1 = 16; val = square(n1); // Call voidfn static function printf(“The square of the %d : %dn”, n1, val); voidfn(); // Call intfn static function val = intfn(n1); printf(“The square root of the %d : %dn”, n1, val); return 0; } Output When you run this code,

C – NULL Pointer

NULL Pointer in C ”; Previous Next NULL Pointer in C A NULL pointer in C is a pointer that doesn”t point to any of the memory locations. The NULL constant is defined in the header files stdio.h, stddef.h as well as stdlib.h. A pointer is initialized to NULL to avoid the unpredicted behavior of a program or to prevent segmentation fault errors. Declare and Initialize a NULL Pointer This is how you would declare and initialize a NULL pointer − type *ptr = NULL; Or, you can use this syntax too − type *ptr = 0; Example of a NULL Pointer The following example demonstrates how to declare and initialize a NULL pointer − #include <stdio.h> int main() { int *p= NULL;//initialize the pointer as null. printf(“The value of pointer is %u”,p); return 0; } Output When you run this code, it will produce the following output − The value of pointer is 0. Applications of NULL Pointer Following are some of the applications of a NULL pointer − To initialize a pointer variable when that pointer variable isn”t assigned any valid memory address yet. To pass a null pointer to a function argument when we don”t want to pass any valid memory address. To check for a null pointer before accessing any pointer variable so that we can perform error handling in pointer-related code. For example, dereference a pointer variable only if it”s not NULL. A NULL pointer is always used to detect the endpoint of trees, linked lists, and other dynamic data structures. Check Whether a Pointer is NULL It is always recommended to check whether a pointer is NULL before dereferencing it to fetch the value of its target variable. Example Take a look at the following example − #include <stdio.h> int main(){ int *ptr = NULL; // null pointer if (ptr == NULL) { printf(“Pointer is a NULL pointer”); } else { printf(“Value stored in the address referred by the pointer: %d”, *ptr); } return 0; } Output When you run this code, it will produce the following output − Pointer is a NULL pointer Check Memory Allocation Using NULL Pointer The malloc() and calloc() functions are used to dynamically allocate a block of memory. On success, these functions return the pointer to the allocated block; whereas on failure, they return NULL. Example The following example shows how you can use the NULL pointer to check whether memory allocation was successful or not − #include <stdio.h> #include <stdlib.h> int main(){ int* ptr = (int*)malloc(sizeof(int)); if (ptr == NULL){ printf(“Memory Allocation Failed”); exit(0); } else{ printf(“Memory Allocated successfully”); } return 0; } Output Run the code and check its output − Memory Allocated successfully NULL File Pointer Checking if the FILE pointer returned by the fopen() function is NULL is always a recommended approach to avoid runtime errors in file-related processing. Example The following example shows how you can use the NULL file pointer to ensure that a file is accessible or not − #include <stdio.h> #include <string.h> int main(){ FILE *fp; char *s; int i, a; float p; fp = fopen (“file3.txt”, “r”); if (fp == NULL){ puts (“Cannot open file”); return 0; } while (fscanf(fp, “%d %f %s”, &a, &p, s) != EOF) printf (“Name: %s Age: %d Percent: %fn”, s, a, p); fclose(fp); return 0; } You should always initialize a pointer variable to NULL when the target variable hasn”t been assigned any valid memory address yet. Print Page Previous Next Advertisements ”;