Structures in C ”; Previous Next Structures in C A structure in C is a derived or user-defined data type. We use the keyword struct to define a custom data type that groups together the elements of different types. The difference between an array and a structure is that an array is a homogenous collection of similar types, whereas a structure can have elements of different types stored adjacently and identified by a name. We are often required to work with values of different data types having certain relationships among them. For example, a book is described by its title (string), author (string), price (double), number of pages (integer), etc. Instead of using four different variables, these values can be stored in a single struct variable. Declare (Create) a Structure You can create (declare) a structure by using the “struct” keyword followed by the structure_tag (structure name) and declare all of the members of the structure inside the curly braces along with their 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. Syntax of Structure Declaration The format (syntax) to declare a structure is as follows − struct [structure tag]{ member definition; member definition; … member definition; } [one or more structure variables]; 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. Example In the following example we are declaring a structure for Book to store the details of a Book − struct book{ char title[50]; char author[50]; double price; int pages; } book1; Here, we declared the structure variable book1 at the end of the structure definition. However, you can do it separately in a different statement. Structure Variable Declaration To access and manipulate the members of the structure, you need to declare its variable first. To declare a structure variable, write the structure name along with the “struct” keyword followed by the name of the structure variable. This structure variable will be used to access and manipulate the structure members. Example The following statement demonstrates how to declare (create) a structure variable struct book book1; Usually, a structure is declared before the first function is defined in the program, after the include statements. That way, the derived type can be used for declaring its variable inside any function. Structure Initialization The initialization of a struct variable is done by placing the value of each element inside curly brackets. Example The following statement demonstrates the initialization of structure struct book book1 = {“Learn C”, “Dennis Ritchie”, 675.50, 325}; Accessing the Structure Members To access the members of a structure, first, you need to declare a structure variable and then use the dot (.) operator along with the structure variable. Example 1 The four elements of the struct variable book1 are accessed with the dot (.) operator. Hence, “book1.title” refers to the title element, “book1.author” is the author name, “book1.price” is the price, “book1.pages” is the fourth element (number of pages). Take a look at the following example − #include <stdio.h> struct book{ char title[10]; char author[20]; double price; int pages; }; int main(){ struct book book1 = {“Learn C”, “Dennis Ritchie”, 675.50, 325}; printf(“Title: %s n”, book1.title); printf(“Author: %s n”, book1.author); printf(“Price: %lfn”, book1.price); printf(“Pages: %d n”, book1.pages); printf(“Size of book struct: %d”, sizeof(struct book)); return 0; } Output Run the code and check its output − Title: Learn C Author: Dennis Ritchie Price: 675.500000 Pages: 325 Size of book struct: 48 Example 2 In the above program, we will make a small modification. Here, we will put the type definition and the variable declaration together, like this − struct book{ char title[10]; char author[20]; double price; int pages; } book1; Note that if you a declare a struct variable in this way, then you cannot initialize it with curly brackets. Instead, the elements need to be assigned individually. #include <stdio.h> #include <string.h> struct book{ char title[10]; char author[20]; double price; int pages; } book1; int main(){ strcpy(book1.title, “Learn C”); strcpy(book1.author, “Dennis Ritchie”); book1.price = 675.50; book1.pages = 325; printf(“Title: %s n”, book1.title); printf(“Author: %s n”, book1.author); printf(“Price: %lf n”, book1.price); printf(“Pages: %d n”, book1.pages); return 0; } Output When you execute this code, it will produce the following output − Title: Learn C Author: Dennis Ritchie Price: 675.500000 Pages: 325 Copying Structures The assignment (=) operator can be used to copy a structure directly. You can also use the assignment operator (=) to assign the value of the member of one structure to another. Let”s have two struct book variables, book1 and book2. The variable book1 is initialized with declaration, and we wish to assign the same values of its elements to that of book2. We can assign individual elements as follows − struct book book1 = {“Learn C”, “Dennis Ritchie”, 675.50, 325}, book2; strcpy(book2.title, book1.title); strcpy(book2.author, book1.author); book2.price = book1.price; book2.pages = book1.pages; Note the use of strcpy() function to assign the value to a string variable instead of using the “= operator”. Example You can also assign book1 to book2 so that all the elements of book1 are respectively assigned to the elements of book2. Take a look at the following program code − #include <stdio.h> #include <string.h> struct book{ char title[10];
Category: cprogramming
C – Pointer to an Array
Pointer to an Array in C ”; Previous Next An array name is a constant pointer to the first element of the array. Therefore, in this declaration, int balance[5]; balance is a pointer to &balance[0], which is the address of the first element of the array. Example In this code, we have a pointer ptr that points to the address of the first element of an integer array called balance. #include <stdio.h> int main(){ int *ptr; int balance[5] = {1, 2, 3, 4, 5}; ptr = balance; printf(“Pointer ”ptr” points to the address: %d”, ptr); printf(“nAddress of the first element: %d”, balance); printf(“nAddress of the first element: %d”, &balance[0]); return 0; } Output In all the three cases, you get the same output − Pointer ”ptr” points to the address: 647772240 Address of the first element: 647772240 Address of the first element: 647772240 If you fetch the value stored at the address that ptr points to, that is *ptr, then it will return 1. Array Names as Constant Pointers It is legal to use array names as constant pointers and vice versa. Therefore, *(balance + 4) is a legitimate way of accessing the data at balance[4]. Once you store the address of the first element in “ptr“, you can access the array elements using *ptr, *(ptr + 1), *(ptr + 2), and so on. Example The following example demonstrates all the concepts discussed above − #include <stdio.h> int main(){ /* an array with 5 elements */ double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0}; double *ptr; int i; ptr = balance; /* output each array element”s value */ printf(“Array values using pointer: n”); for(i = 0; i < 5; i++){ printf(“*(ptr + %d): %fn”, i, *(ptr + i)); } printf(“nArray values using balance as address:n”); for(i = 0; i < 5; i++){ printf(“*(balance + %d): %fn”, i, *(balance + i)); } return 0; } Output When you run this code, it will produce the following output − Array values using pointer: *(ptr + 0): 1000.000000 *(ptr + 1): 2.000000 *(ptr + 2): 3.400000 *(ptr + 3): 17.000000 *(ptr + 4): 50.000000 Array values using balance as address: *(balance + 0): 1000.000000 *(balance + 1): 2.000000 *(balance + 2): 3.400000 *(balance + 3): 17.000000 *(balance + 4): 50.000000 In the above example, ptr is a pointer that can store the address of a variable of double type. Once we have the address in ptr, *ptr will give us the value available at the address stored in ptr. Print Page Previous Next Advertisements ”;
C – nested switch statements
C – Nested Switch Statements ”; Previous Next It is possible to have a switch as a part of the statement sequence of an outer switch. Even if the case constants of the inner and outer switch contain common values, no conflicts will arise. Syntax The syntax for a nested switch statement is as follows − switch(ch1){ case ”A”: printf(“This A is part of outer switch” ); switch(ch2) { case ”A”: printf(“This A is part of inner switch” ); break; case ”B”: /* case code */ } break; case ”B”: /* case code */ } Example Take a look at the following example − #include <stdio.h> int main (){ /* local variable definition */ int a = 100; int b = 200; switch(a){ case 100: printf(“This is part of outer switchn”, a); switch(b){ case 200: printf(“This is part of inner switchn”, a); } } printf(“Exact value of a is: %dn”, a); printf(“Exact value of b is: %dn”, b); return 0; } Output When the above code is compiled and executed, it produces the following output − This is part of outer switch This is part of inner switch Exact value of a is : 100 Exact value of b is : 200 Nested Switch-Case Statements in C Just like nested if–else, you can have nested switch-case constructs. You may have a different switch-case construct each inside the code block of one or more case labels of the outer switch scope. The nesting of switch-case can be done as follows − switch (exp1){ case val1: switch (exp2){ case val_a: stmts; break; case val_b: stmts; break; } case val2: switch (expr2){ case val_c: stmts; break; case val_d: stmts; break; } } Example Here is a simple program to demonstrate the syntax of Nested Switch Statements in C − #include <stdio.h> int main(){ int x = 1, y = ”b”, z=”X”; // Outer Switch switch (x){ case 1: printf(“Case 1 n”); switch (y){ case ”a”: printf(“Case a n”); break; case ”b”: printf(“Case b n”); break; } break; case 2: printf(“Case 2 n”); switch (z){ case ”X”: printf(“Case X n”); break; case ”Y”: printf(“Case Y n”); break; } } return 0; } Output When you run this code, it will produce the following output − Case 1 Case b Change the values of the variables (x, y, and z) and check the output again. The output depends on the values of these three variables. c_decision_making.htm Print Page Previous Next Advertisements ”;
C – Operator Precedence
Operator Precedence in C ”; Previous Next A single expression in C may have multiple operators of different types. The C compiler evaluates its value based on the operator precedence and associativity of operators. The precedence of operators determines the order in which they are evaluated in an expression. Operators with higher precedence are evaluated first. For example, take a look at this expression − x = 7 + 3 * 2; Here, the multiplication operator “*” has a higher precedence than the addition operator “+”. So, the multiplication 3*2 is performed first and then adds into 7, resulting in “x = 13”. The following table lists the order of precedence of operators in C. Here, operators with the highest precedence appear at the top of the table, and those with the lowest appear at the bottom. Category Operator Associativity Postfix () [] -> . ++ – – Left to right Unary + – ! ~ ++ – – (type)* & sizeof Right to left Multiplicative * / % Left to right Additive + – Left to right Shift << >> Left to right Relational < <= > >= Left to right Equality == != Left to right Bitwise AND & Left to right Bitwise XOR ^ Left to right Bitwise OR | Left to right Logical AND && Left to right Logical OR || Left to right Conditional ?: Right to left Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left Comma , Left to right Within an expression, higher precedence operators will be evaluated first. Operator Associativity In C, the associativity of operators refers to the direction (left to right or right to left) an expression is evaluated within a program. Operator associativity is used when two operators of the same precedence appear in an expression. In the following example − 15 / 5 * 2 Both the “/” (division) and “*” (multiplication) operators have the same precedence, so the order of evaluation will be decided by associativity. As per the above table, the associativity of the multiplicative operators is from Left to Right. So, the expression is evaluated as − (15 / 5) * 2 It evaluates to − 3 * 2 = 6 Example 1 In the following code, the multiplication and division operators have higher precedence than the addition operator. The left−to−right associativity of multiplicative operator results in multiplication of “b” and “c” divided by “e“. The result then adds up to the value of “a“. #include <stdio.h> int main(){ int a = 20; int b = 10; int c = 15; int d = 5; int e; e = a + b * c / d; printf(“e : %dn” , e ); return 0; } Output When you run this code, it will produce the following output − e: 50 Example 2 We can use parenthesis to change the order of evaluation. Parenthesis () got the highest priority among all the C operators. #include <stdio.h> int main(){ int a = 20; int b = 10; int c = 15; int d = 5; int e; e = (a + b) * c / d; printf(“e: %dn”, e); return 0; } Output Run the code and check its output − e: 90 In this expression, the addition of a and b in parenthesis is first. The result is multiplied by c and then the division by d takes place. Example 3 In the expression that calculates e, we have placed a+b in one parenthesis, and c/d in another, multiplying the result of the two. #include <stdio.h> int main(){ int a = 20; int b = 10; int c = 15; int d = 5; int e; e = (a + b) * (c / d); printf(“e: %dn”, e ); return 0; } Output On running this code, you will get the following output − e: 90 Precedence of Post / Prefix Increment / Decrement Operators The “++” and “− −” operators act as increment and decrement operators, respectively. They are unary in nature and can be used as a prefix or postfix to a variable. When used as a standalone, using these operators in a prefix or post−fix manner has the same effect. In other words, “a++” has the same effect as “++a”. However, when these “++” or “− −” operators appear along with other operators in an expression, they behave differently. Postfix increment and decrement operators have higher precedence than prefix increment and decrement operators. Example The following example shows how you can use the increment and decrement operators in a C program − #include <stdio.h> int main(){ int x = 5, y = 5, z; printf(“x: %d n”, x); z = x++; printf(“Postfix increment: x: %d z: %dn”, x, z); z = ++y; printf(“Prefix increment. y: %d z: %dn”, y ,z); return 0; } Output Run the code and check its output − x: 5 Postfix increment: x: 6 z: 5 Prefix increment. y: 6 z: 6
Structure Padding and Packing in C ”; Previous Next What is Structure Padding in C? Structure padding in C is the process that is handled by the CPU architecture. Structure Padding adds a certain number of empty bytes within a structure so that the data members are naturally aligned in memory. The alignment requirements are determined by the processor architecture rather than the language itself. Naturally, the alignment requirements change as per the data bus size or other architectural considerations of a certain CPU architecture. Understanding Structure Padding with Examples Let us define a struct type as follows − struct struct1 { char x; int y; char z; }; Example 1 Let us check the size in bytes required for a variable of this type − #include <stdio.h> struct struct1{ char a; char b; int c; }; int main(){ printf(“Size: %d”, sizeof(struct struct1)); return 0; } Output When you run this code, it will produce the following output − Size: 8 The result is contrary to the expectation. Considering that a char type needs 1 byte, and an int type needs 4 bytes, one might assume the output should be “1 + 1 + 4 = 6 bytes”. However, the CPU architecture necessitates altering this structure. Considering that we are using a CPU with 32-bit processor, it reads 4 bytes at a time, which means that 1 word is equal to 4 bytes. In one CPU cycle, it accesses the char “a”, then char “b” and the first two bytes of int “c”. In the second cycle, the other two bytes are accessed. Even if we want to read only “c”, two CPU cycles are required. For this purpose, the CPU adds two empty bytes before the bytes in which the value of “c” is stored. This mechanism is called as padding. This now explains the result we obtained above, that of the size of the struct type to be 8 bytes. Example 2 Let us change the sequence of members in the above struct type, and set the type of “b” and the type of “c“. #include <stdio.h> struct struct1{ char a; int b; char c; }; int main(){ printf(“size: %d”, sizeof(struct struct1)); return 0; } Output Run the code and check its output − size: 12 Out of the 4 bytes in the first word, the first one is allocated to char “a” followed by three empty bytes. The next 4 bytes that form the next word are used to store int “b”. Subsequently, out of the next group of 4, only one is utilized for “c”. However, the struct size is 12. What is Structure Packing in C? Structure packing, on the other hand, is a mechanism for minimizing the effect of padding, thereby trying and reduce wasted memory space. We can use certain pragma directives and attributes to achieve packing. Understanding Structure Packing with Examples The padding, forced by the CPU architecture is unavoidable, however there are ways to minimize padding. It can be done with the use of − Using #pragma pack(1) directive Using packed attribute Using #pragma pack(1) Directive The #pragma pack(1) preprocessor directive forces the compiler to disregard the padding, and align the structure members end to end during the memory allocation process. Example Let”s add this directive at the top of the code used previously, and see the result − #include <stdio.h> #pragma pack(1) struct struct1{ char a; int b; char c; }; int main(){ printf(“size: %d”, sizeof(struct struct1)); return 0; } Output Run the code and check its output − size: 6 We can see the structure padding has been avoided and reduced memory wastage. Using __attribute__((packed)) With GCC, we can use attributes to specify various special properties of structure and union types. The attributes are: aligned, deprecated, packed, transparent_union, unused, and visibility. The syntax of applying these attributes is “__attribute__ ((…))“. Example Here, we are going to use packed attribute in the definition of our struct type. #include <stdio.h> struct __attribute__((packed)) struct1{ char a; int b; char c; }; int main(){ printf(“size: %d”, sizeof(struct struct1)); return 0; } Output Run the code and check its output − size: 6 This method also avoids the effect of padding. Print Page Previous Next Advertisements ”;
C – For loop
For Loop in C ”; Previous Next Most programming languages including C support the for keyword for constructing a loop. In C, the other loop-related keywords are while and do-while. Unlike the other two types, the for loop is called an automatic loop, and is usually the first choice of the programmers. The for loop is an entry-controlled loop that executes the statements till the given condition. All the elements (initialization, test condition, and increment) are placed together to form a for loop inside the parenthesis with the for keyword. Syntax of for Loop The syntax of the for loop in C programming language is − for (init; condition; increment){ statement(s); } Control Flow of a For Loop Here is how the control flows in a “for” loop − The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears. Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and the control jumps to the next statement just after the “for” loop. After the body of the “for” loop executes, the control flow jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition. The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again the condition). After the condition becomes false, the “for” loop terminates. Flowchart of for Loop The following flowchart represents how the for loop works − Developers prefer to use for loops when they know in advance how many number of iterations are to be performed. It can be thought of as a shorthand for while and do-while loops that increment and test a loop variable. The for loop may be employed with different variations. Let us understand how the for loop works in different situations. Example: Basic for Loop This is the most basic form of the for loop. Note that all the three clauses inside the parenthesis (in front of the for keyword) are optional. #include <stdio.h> int main(){ int a; // for loop execution for(a = 1; a <= 5; a++){ printf(“a: %dn”, a); } return 0; } Output Run the code and check its output − a: 1 a: 2 a: 3 a: 4 a: 5 Initializing for Loop Counter Before Loop Statement The initialization step can be placed above the header of the for loop. In that case, the init part must be left empty by putting a semicolon. Example #include <stdio.h> int main(){ int a = 1; // for loop execution for( ; a <= 5; a++){ printf(“a: %dn”, a); } return 0; } Output You still get the same output − a: 1 a: 2 a: 3 a: 4 a: 5 Updating Loop Counter Inside for Loop Body You can also put an empty statement in place of the increment clause. However, you need to put the increment statement inside the body of the loop, otherwise it becomes an infinite loop. Example #include <stdio.h> int main(){ int a; // for loop execution for(a = 1; a <= 5; ){ printf(“a: %dn”, a); a++; } return 0; } Output Here too, you will get the same output as in the previous example − a: 1 a: 2 a: 3 a: 4 a: 5 Using Test Condition Inside for Loop Body You can also omit the second clause of the test condition in the parenthesis. In that case, you will need to terminate the loop with a break statement, otherwise the loop runs infinitely. Example #include <stdio.h> int main(){ int a; // for loop execution for(a = 1; ; a++){ printf(“a: %dn”, a); if(a == 5) break; } return 0; } Output On executing this code, you will get the following output − a: 1 a: 2 a: 3 a: 4 a: 5 Using for Loops with Multiple Counters There may be initialization of more than one variables and/or multiple increment statements in a for statement. However, there can be only one test condition. Example #include <stdio.h> int main(){ int a, b; // for loop execution for(a = 1, b = 1; a <= 5; a++, b++){ printf(“a: %d b: %d a*b: %dn”, a, b, a*b); } return 0; } Output When you run this code, it will produce the following output − a: 1 b: 1 a*b: 1 a: 2 b: 2 a*b: 4 a: 3 b: 3 a*b: 9 a: 4 b: 4 a*b: 16 a: 5 b: 5 a*b: 25 Decrement in for Loop You can also form a decrementing for loop. In this case, the initial value of the looping variable is more than its value in the test condition. The last clause in the for statement uses decrement operator. Example The following program prints the numbers 5 to 1, in decreasing order − #include <stdio.h> int main(){ int a; // for loop execution for(a = 5; a >= 1; a–){ printf(“a: %dn”, a); } return 0; } Output Run the code and check its output − a: 5 a: 4 a: 3 a: 2 a: 1 Traversing Arrays with for Loops
C – Do…while loop
Do-While Loop in C ”; Previous Next The do-while loop is one of the most frequently used types of loops in C. The do and while keywords are used together to form a loop. The do-while is an exit-verified loop where the test condition is checked after executing the loop”s body. Whereas the while loop is an entry-verified. The for loop, on the other hand, is an automatic loop. Syntax of do while Loop The syntax of do-while loop in C is − do { statement(s); } while(condition); How do while Loop Works? The loop construct starts with the keword do. It is then followed by a block of statements inside the curly brackets. The while keyword follows the right curly bracket. There is a parenthesis in front of while, in which there should be a Boolean expression. Now let”s understand how the while loop works. As the C compiler encounters the do keyword, the program control enters and executes the code block marked by the curly brackets. As the end of the code block is reached, the expression in front of the while keyword is evaluated. If the expression is true, the program control returns back to the top of loop. If the expression is false, the compiler stops going back to the top of loop block, and proceeds to the immediately next statement after the block. Note that there is a semicolon at the end of while statement. Flowchart of do while Loop The following flowchart represents how the do-while loop works − Since the expression that controls the loop is tested after the program runs the looping block for the first time, the do-while loop is called an “exit-verified loop”. Here, the key point to note is that a do-while loop makes sure that the loop gets executed at least once. The while keyword implies that the compiler continues to execute the ensuing block as long as the expression is true. However, since the condition sits at the end of the looping construct, it is checked after each iteration (rather than before each iteration as in the case of a while loop). The program performs its first iteration unconditionally, and then tests the condition. If found to be true, the compiler performs the next iteration. As soon as the expression is found to be false, the loop body will be skipped and the first statement after the while loop will be executed. Let us try to understand the behaviour of the while loop with a few examples. Example of do while Loop The following program prints the Hello world message five times. #include <stdio.h> int main(){ // local variable definition int a = 1; // while loop execution do{ printf(“Hello Worldn”); a++; } while(a <= 5); printf(“End of loop”); return 0; } Output Here, the do-while loop acts as a counted loop. Run the code and check its output − Hello World Hello World Hello World Hello World Hello World End of loop The variable “a” that controls the number of repetitions is initialized to 1. The program enters the loop unconditionally, prints the message, increments “a” by 1. As it reaches the end of the loop, the condition in the while statement is tested. Since the condition “a <= 5” is true, the program goes back to the top of the loop and re-enters the loop. Now “a” is 2, hence the condition is still true, hence the loop repeats again, and continues till the condition turns false. The loop stops repeating, and the program control goes to the step after the block. Now, change the initial value of “a” to 10 and run the code again. It will produce the following output − Hello World End of loop This is because the program enters the looping block unconditionally. Since the condition before the while keyword is false, hence the block is not repeated for the next time. Hence, the do-while loop takes at least one iteration as the test condition is at the end of the loop. For this reason, do-while loop is called an “exit-verified loop”. Difference Between while and do while Loops The loops constructed with while and do-while appear similar. You can easily convert a while loop into a do-while loop and vice versa. However, there are certain key differences between the two. The obvious syntactic difference is that the do-while construct starts with the do keyword and ends with the while keyword. The while loop doesn”t need the do keyword. Secondly, you find a semicolon in front of while in case of a do-while loop. There is no semicolon in while loops. Example The location of the test condition that controls the loop is the major difference between the two. The test condition is at the beginning of a while loop, whereas it is at the end in case of a do-while loop. How does it affect the looping behaviour? Look at the following code − #include <stdio.h> int main(){ // local variable definition int a = 0, b = 0; // while loop execution printf(“Output of while loop: n”); while(a < 5){ a++; printf(“a: %dn”, a); } printf(“Output of do-while loop: n”); do{ b++; printf(“b: %dn”,b); } while(b < 5); return 0; } Output Initially, “a” and “b” are initialized to “0” and the output of both the loops is same. Output of while loop: a: 1 a: 2 a: 3 a: 4 a: 5 Output of do-while loop: b: 1 b: 2 b: 3 b: 4 b: 5 Now change the initial value of both the variables to 3 and run the code again. There”s
Initialization of Pointer Arrays in C ”; Previous Next A pointer is a variable that stores the address of another variable. The name of the pointer variable must be prefixed by the “*” symbol. Just as in the case of a normal variable, we can also declare an “array of pointers”, where each subscript of the array holds the address of an array type. How to Initialize Array of Pointers in C? A pointer variable can be initialized at the time of declaration, by assigning it the address of an existing variable. The following snippet shows how you can initialize a pointer − int x = 10; int *y = &x; By default, all the variables including the pointer variables belong to the “auto storage class”. It means that a pointer variable will store an unpredictable, garbage, random memory address, which can lead to undefined behavior and potential risks to a program, such as segmentation fault errors. Hence, it should be initialized to NULL if we don’t have a specific value to store at the time of declaration. int *ptr = NULL; A “pointer array” stores the address in each element. The type of the array must match with the type of the target variable. Initialize Array of Pointers Using static Keyword You can also use the static keyword to initialize an array of pointers to store “0” in each subscript. Example #include <stdio.h> int main(){ static int *ptr[5]; for (int i = 0; i < 5; i++){ printf(“ptr[%d] = %dn”, i, ptr[i]); } return 0; } Output Run the code and check its output − ptr[0]= 0 ptr[1]= 0 ptr[2]= 0 ptr[3]= 0 ptr[4]= 0 Initialize Array of Integer Pointers Here, we declare an array of integer pointers and store the addresses of three integer variables. Example #include <stdio.h> int main(){ int a = 10, b = 20, c = 30; int *ptr[3] = {&a, &b, &c}; for (int i = 0; i < 3; i++){ printf(“ptr[%d]: address: %d value: %dn”, i, ptr[i], *ptr[i]); } return 0; } Output Run the code and check its output − ptr[0]: address: 6422040 value: 10 ptr[1]: address: 6422036 value: 20 ptr[2]: address: 6422032 value: 30 Initialize Array of Pointer by Direct Addresses We can store the address of each element of a normal array in the corresponding element of a pointer array. Example #include <stdio.h> int main(){ int arr[] = {10, 20, 30}; int *ptr[3] = {&arr[0], &arr[1], &arr[2]}; for (int i = 0; i < 3; i++){ printf(“ptr[%d]: address: %d value: %dn”, i, ptr[i], *ptr[i]); } return 0; } Output Run the code and check its output − ptr[0]: address: 6422032 value: 10 ptr[1]: address: 6422036 value: 20 ptr[2]: address: 6422040 value: 30 Traversing an Array with its Base Address When we obtain the base address of an array (in this case “&arr[0]”), we can obtain the addresses of its subsequent elements, knowing that the pointer increments by the size of the data type. Hence, just with the base address (the name of the array is the same of the address of the 0th element), we can traverse an array. Example 1 Take a look at the following example − #include <stdio.h> int main(){ int arr[] = {10, 20, 30}; int *ptr=arr; for (int i = 0; i < 3; i++){ printf(“ptr[%d]: address: %d value: %dn”, i,ptr+i, *(ptr+i)); } return 0; } Output Run the code and check its output − ptr[0]: address: 6422020 value: 10 ptr[1]: address: 6422024 value: 20 ptr[2]: address: 6422028 value: 30 Example 2: Traversing a 2D Array using a Pointer Array In this example, we have a 2D array. The address of the 0th element of each row is stored in a pointer array. When traversing, the address stored in each element of the pointer array, that points to the 0th element of the corresponding row, each incremented to fetch the values in each row. #include <stdio.h> int main(){ // 2d array int arr[3][4] = { {1, 2, 3, 4}, {5, 6, 7, 8}, }; int ROWS = 2, COLS = 4; int i, j; // pointer int (*ptr)[4] = arr; // print the element of the array via pointer ptr for (i = 0; i < ROWS; i++) { for (j = 0; j < COLS; j++) { printf(“%d “, *(ptr[i]+j)); } printf(“n”); } return 0; } Output When you run this code, it will produce the following output − 1 2 3 4 5 6 7 8 Example 3 We don’t really need a pointer array here, as we can use the name of this 2D array as its base pointer, and increment it row and column-wise to fetch the elements in the given 2D array − #include <stdio.h> int main(){ // 2d array int arr[3][4] = { {1, 2, 3, 4}, {5, 6, 7, 8}, }; int ROWS = 2, COLS = 4; int i, j; // pointer int *ptr = arr; // print the element of the array via pointer ptr for (i = 0; i < ROWS; i++){ for (j = 0; j < COLS; j++){ printf(“%d “, *(ptr + i * COLS + j)); } printf(“n”); } return 0; } Output The output resembles that of the previous code − 1 2 3 4 5 6 7 8 Initialize Array of Character Pointers (String) In C programming, a string is an array of char data type. Since
Passing Pointers to Functions in C ”; Previous Next A pointer In C is a variable that stores the address of another variable. It acts as a reference to the original variable. A pointer can be passed to a function, just like any other argument is passed. A function in C can be called in two ways − Call by Value Call by Reference To call a function by reference, you need to define it to receive the pointer to a variable in the calling function. Here is the syntax that you would use to call a function by reference − type function_name(type *var1, type *var2, …) When a function is called by reference, the pointers of the actual argument variables are passed, instead of their values. Advantages of Passing Pointers to Functions Passing a pointer to a function has two advantages − It overcomes the limitation of pass by value. Changes to the value inside the called function are done directly at the address stored in the pointer. Hence, we can manipulate the variables in one scope from another. It also overcomes the limitation of a function that it can return only one expression. By passing pointers, the effect of processing of a function takes place directly at the address. Secondly, more than one values can be returned if we return a pointer of an array or struct variable. In this chapter, we shall see how to − Pass pointers to int variables Pass pointers to array Pass pointer to structure Example of Passing Pointers to Functions Let us define a function add() that receives the references of two variables. When such a function is called, we pass the address of the actual argument. Let us call the add() function by reference from inside the main() function. #include <stdio.h> /* function declaration */ int add(int *, int *); int main(){ int a = 10, b = 20; int c = add(&a, &b); printf(“Addition: %d”, c); } int add(int *x, int *y){ int z = *x + *y; return z; } Output Addition: 30 Swap Values by Passing Pointers One of the most cited applications of passing a pointer to a function is how we can swap the values of two variables. The following function receives the reference of two variables whose values are to be swapped − /* function definition to swap the values */ int swap(int *x, int *y){ int z; z = *x; /* save the value at address x */ *x = *y; /* put y into x */ *y = z; /* put z into y */ return 0; } Example The main() function has two variables a and b; their addresses are passed as arguments to the swap() function. #include <stdio.h> int swap(int *x, int *y){ int z; z = *x; *x = *y; *y = z; } int main (){ /* local variable definition */ int a = 10; int b = 20; printf(“Before swap, value of a: %dn”, a); printf(“Before swap, value of b: %dn”, b); /* calling a function to swap the values */ swap(&a, &b); printf(“After swap, value of a: %dn”, a); printf(“After swap, value of b: %dn”, b); return 0; } Output When you execute this code, it will produce the following output − Before swap, value of a: 10 Before swap, value of b: 20 After swap, value of a: 20 After swap, value of b: 10 Passing an Array Pointer to a Function In C programming, the name of an array acts the address of the first element of the array; in other words, it becomes a pointer to the array. Example In this example, we declare an uninitialized array in main() and pass its pointer to a function along with an integer. Inside the function, the array is filled with the square, cube and square root of the passed integer. The function returns the pointer of this array, using which the values are accessed and printed in the main() function. #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 When you run this code, it will produce the following output − Square of 100: 10000.000000 cube of 100: 1000000.000000 Square root of 100: 10.000000 Passing String Pointers to a Function Let us have a look at another example, where we will pass string pointers to a function. Example In this program, two strings are passed to the compare() function. A string in C is an array of char data type. We use the strlen() function to find the length of the string. #include <stdio.h> int compare(char *, char *); int main(){ char str1[] = “BAT”; char str2[] = “BALL”; int ret = compare(str1, str2); return 0; } int compare (char *x, char *y){ int val; if (strlen(x) > strlen(y)){ printf(“Length of Str1 is greater than or equal to the length of Str2”); } else{ printf(“Length of Str1 is less than the length of Str2”); } } Output When you run this code, it will produce the following output − Length of Str1 is less than the length of Str2 Passing Struct Pointer to a Function In C programming,
C – Global Variables
Global Variables in C ”; Previous Next Global variables are defined outside a function, usually at the top of a program. Global variables hold their values throughout the lifetime of a program and they can be accessed inside any of the functions defined for the program. If a function accesses and modifies the value of a global variable, then the updated value is available for other function calls. If a variable defined in a certain file, then you can still access it inside another code module as a global variable by using the extern keyword. The extern keyword can also be used to access a global variable instead of a local variable of the same name. Declaring Global Variable The declaration of a global variable in C is similar to the declaration of the normal (local) variables but global variables are declared outside of the functions. Consider the following syntax to declare a global variable: data_type variable_name; // main or any function int main() { } Example of Global Variable in C The following program shows how global variables are used in a program: #include <stdio.h> /* global variable declaration */ int g = 10; int main(){ /* local variable declaration */ int a; /* actual initialization */ a = g * 2; printf(“Value of a = %d, and g = %dn”, a, g); return 0; } Output When you run this code, it will produce the following output − Value of a = 20, and g = 10 Accessing Global Variables Global variables are accessible in all the functions in a C program. If any function updates the value of a global variable, then its updated value will subsequently be available for all the other functions. Example of Accessing Global Variables The following example demonstrates the example of accessing global variables in C language: #include <stdio.h> /* global variable declaration */ int g = 10; int function1(); int function2(); int main(){ printf(“Value of Global variable g = %dn”, g); function1(); printf(“Updated value of Global variable g = %dn”, g); function2(); printf(“Updated value of Global variable g = %dn”, g); return 0; } int function1(){ g = g + 10; printf(“New value of g in function1(): %dn”, g); return 0; } int function2(){ printf(“The value of g in function2(): %dn”, g); g = g + 10; return 0; } Run the code and check its output − Value of Global variable g = 10 New value of g in function1(): 20 Updated value of Global variable g = 20 The value of g in function2(): 20 Updated value of Global variable g = 30 Scope and Accessibility of Global Variables Global variables are available to only those functions which are defined after their declaration. Global variables are declared outside of any function, so they can be accessed by all functions within the same file by default. Example In this example, we declared a global variable (x) before the main() function. There is another global variable y that is declared after the main() function but before function1(). In such a case, the variable y, even thought it is a global variable, is not available for use in the main() function, as it is declared afterwards. As a result, you get an error. #include <stdio.h> /* global variable declaration */ int x = 10; int function1(); int main(){ printf(“value of Global variable x= %d y=%dn”, x, y); function1(); return 0; } int y = 20; int function1(){ printf (“Value of Global variable x = %d y = %dn”, x, y); } When you run this code, it will produce an error − Line no 11: error: ”y” undeclared (first use in this function) 11 | printf (“Value of Global variable x = %d y = %dn”, x, y); | ^ Accessing Global Variables With extern Keyword If you want to access a global variable when a local variable with same name is also there in the program, then you should use the extern keyword. Example In this C Program, we have a global variable and a local variable with the same name (x). Now, let”s see how we can use the keyword “extern” to avoid confusion − #include <stdio.h> // Global variable x int x = 50; int main(){ // Local variable x int x = 10;{ extern int x; printf(“Value of global x is %dn”, x); } printf(“Value of local x is %dn”, x); return 0; } Output When you run this code, it will produce the following output − Value of global x is 50 Value of local x is 10 Avoid Using Global Variables Global variables can simplify the programming logic. Global variables can be accessed across functions and you need not use a parameter passing technique to pass variables from one function to another. However, it is not wise or efficient to have too many global variables in a C program, as the memory occupied by these variables is not released till the end of the program. Using global declaration is not considered a good programming practice because it doesn’t implement structured approach. Global declaration is also not advised from security point of view, as they are accessible to all the functions. Finally, using global declarations can make a program difficult to debug, maintain, and scale up. Print Page Previous Next Advertisements ”;