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 ”;

C – Passing Arrays to Function

Passing Arrays as Function Arguments in C ”; Previous Next If you want to pass an array to a function, you can use either call by value or call by reference method. In call by value method, the argument to the function should be an initialized array, or an array of fixed size equal to the size of the array to be passed. In call by reference method, the function argument is a pointer to the array. Pass array with call by value method In the following code, the main() function has an array of integers. A user−defined function average () is called by passing the array to it. The average() function receives the array, and adds its elements using a for loop. It returns a float value representing the average of numbers in the array. Example #include <stdio.h> float average(int arr[5]); int main(){ int arr[] = {10, 34, 21, 78, 5}; float avg = average(arr); printf(“average: %f”, avg); } float average(int arr[5]){ int sum=0; int i; for (i=0; i<5; i++){ printf(“arr[%d]: %dn”, i, arr[i]); sum+=arr[i]; } return (float)sum/5; } Output arr[0]: 10 arr[1]: 34 arr[2]: 21 arr[3]: 78 arr[4]: 5 average: 29.600000 In the following variation, the average() function is defined with two arguments, an uninitialized array without any size specified. The length of the array declared in main() function is obtained by divising the size of the array with the size of int data type. Example #include <stdio.h> float average(int arr[], int length); int main(){ int arr[] = {10, 34, 21, 78, 5}; int length = sizeof(arr)/sizeof(int); float avg = average(arr, length); printf(“average: %f”, avg); } float average(int arr[], int length){ int sum=0; int i; for (i=0; i<length; i++){ printf(“arr[%d]: %dn”, i, arr[i]); sum+=arr[i]; } return (float)sum/length; } Output arr[0]: 10 arr[1]: 34 arr[2]: 21 arr[3]: 78 arr[4]: 5 average: 29.600000 Pass array with call by reference To use this approach, we should understand that elements in an array are of similar data type, stored in continuous memory locations, and the array size depends on the data type. Also, the address of the 0th element is the pointer to the array. In the following example − int a[5] = {1,2,3,4,5}; The size of the array is 20 bytes (4 bytes for each int) Int *x = a; Here x is the pointer to the array. It points to the 0th element. If the pointer is incremented by 1, it points to the next element. Example #include <stdio.h> int main() { int a[] = {1,2,3,4,5}; int *x = a, i; for (i=0; i<5; i++){ printf(“%dn”, *x); x++; } return 0; } Output 1 2 3 4 5 Let us use this characteristics for passing the array by reference. In the main() function, we declare an array and pass its address to the max() function. The max() function traverses the array using the pointer and returns the largest number in the array, back to main() function. Example #include <stdio.h> int max(int *arr, int length); int main(){ int arr[] = {10, 34, 21, 78, 5}; int length = sizeof(arr)/sizeof(int); int maxnum = max(arr, length); printf(“max: %d”, maxnum); } int max(int *arr, int length){ int max=*arr; int i; for (i=0; i<length; i++){ printf(“arr[%d]: %dn”, i, (*arr)); if ((*arr)>max) max = (*arr); arr++; } return max; } Output arr[0]: 10 arr[1]: 34 arr[2]: 21 arr[3]: 78 arr[4]: 5 max: 78 The max() function receives the address of the array from main() in the pointer arr. Each time, when it is incremented, it points to the next element in the original array. The max() function can also access the array elements as a normal subscripted array as in the following definition − int max(int *arr, int length){ int max=*arr; int i; for (i=0; i<length; i++){ printf(“arr[%d]: %dn”, i, arr[i]); if (arr[i]>max) max = arr[i]; } return max; } Pass two−dimensional array to function You can also pass the pointer of a two-dimensional array to a function. Inside the function, the two dimensional array is traversed with a nested for loop construct Example #include <stdio.h> int twoDarr(int *arr); int main(){ int arr[][3]= {10, 34, 21, 78, 5, 25}; twoDarr(*arr); } int twoDarr(int *arr){ int max=*arr; int i, j; for (i=0; i<2; i++){ for (j=0; j<3; j++){ printf(“%dt”, arr[i]); arr++; } printf(“n”); } } Output 10 34 21 5 25 16 Function to compare string lengths In the following program, two strings are passed to compare() functions. In C, as string is an array of char data type. We use strlen() function to find the length of string which is the number of characters in it. Example #include <stdio.h> #include <string.h> int compare( char *, char *); int main() { char a[] = “BAT”; char b[] = “BALL”; int ret = compare(a, b); return 0; } int compare (char *x, char *y){ int val; if (strlen(x)>strlen(y)){ printf(“length of string a is greater than or equal to length of string b”); } else{ printf(“length of string a is less than length of string b”); } } Output length of string a is less than length of string b Print Page Previous Next Advertisements ”;

C – Memory Address

Memory Address in C ”; Previous Next Memory Address in C The memory address is assigned to a variable when a variable is declared in C language. C compiler stores the value of the variable in the different segments of the memory. Segments of Memory Different elements of a C program are stored in different segments of the computer’s memory, which has the following segments − Text segment − A text segment, also known as a code segment or simply as text, is one of the sections of a progris used to store the object version of the C program. Initialized data segment − The global variables and static variables that are initialized by the programmer are allocated the memory in the initialized data segment. Uninitialized data segment − An uninitialized data segment also called as bss (stands for block started by symbol). The program allocates memory for this segment when it loads. Every data in bss is initialized to arithmetic “0” and pointers to null pointer by the kernel before the C program executes. Stack − Stack is a LIFO (last in first out) data structure. Stack segment stores the value of local variables and values of parameters passed to a function. It also maintains the pointer to which a function call returns. Heap − Heap is used for allocating memory during the runtime. All the functions that perform dynamic memory allocation deal with heap. Accessing Memory Address The memory addresses in C can be accessed or specified through the Address of (&) operator. To print a memory address using the printf() function, you need to use %p format specifier. Syntax Below is the syntax to access memory address − &variable_name Example In the following example, we are declaring two variables and printing their memory addresses − #include <stdio.h> int main() { // Declaring two variables int a; int b; // Accessing their memory // addresses and print them printf(“Memory address of a is %pn”, &a); printf(“Memory address of b is %pn”, &b); return 0; } How Does C Compiler Allocate Memory? Memory can be considered of as an array of bytes where each address is on index in the array and holds 1 byte. When you declare a variable in a C program, the C compiler allocates a random memory location to it, depending on the size requirement, which depends on the type. When an int variable is declared − int x = 10; The compiler assigns the value in a random byte address. Since an int type needs 4 bytes, the next four addresses are earmarked for it. C allows you to find out which address has been allocated to a variable. You can use the %p format specifier to print the hexadecimal address of the memory location. char x = ”A”; printf (“address of x: %pn”, &x); This prints the address of “x” in hexadecimal format − Address of x: 000000000061FE1F Example Arrays in C are contiguous memory areas that hold a number of values of the same data type (int, long, *char, etc.). #include <stdio.h> int main() { // initialize an array of ints int numbers[5] = {1,2,3,4,5}; int i = 0; // print the address of the array variable printf(“numbers = %pn”, numbers); // print addresses of each array index do { printf(“numbers[%u] = %pn”, i, (void *)(&numbers[i])); i++; } while(i < 5); // print the size of the array printf(“sizeof(numbers) = %lun”, sizeof(numbers)); } Output When you run this code, it will produce the following output − numbers = 0x7fff0815c0e0 numbers[0] = 0x7fff0815c0e0 numbers[1] = 0x7fff0815c0e4 numbers[2] = 0x7fff0815c0e8 numbers[3] = 0x7fff0815c0ec numbers[4] = 0x7fff0815c0f0 sizeof(numbers) = 20 Print Page Previous Next Advertisements ”;

C – Applications of Pointers

Applications of Pointers in C ”; Previous Next One of the most important features of C is that it provides low-level memory access with the concept of pointers. A pointer is a variable that stores the address of another variable in the memory. The provision of pointers has many applications such as passing arrays and struct type to a function and dynamic memory allocation, etc. In this chapter, we will explain some important applications of pointers in C. To Access Array Elements Array elements can also be accessed through the pointer. You need to declare and initialize a pointer to an array and using it you can access each element by incrementing the pointer variable by 1. The pointer to an array is the address of its 0th element. When the array pointer is incremented by 1, it points to the next element in the array. Example The following example demonstrates how you can traverse an array with the help of its pointer. #include <stdio.h> int main(){ int arr[] = {1,2,3,4,5}; int *ptr = arr; for(int i = 0; i <= 4; i++){ printf(“arr[%d]: %dn”, i, *ptr); ptr++; } return 0; } Output Run the code and check its output − arr[0]: 1 arr[1]: 2 arr[2]: 3 arr[3]: 4 arr[4]: 5 For Allocating Memory Dynamically One of the most important applications of C pointers is to declare memory for the variables dynamically. There are various situations, where static memory allocation cannot solve the problem, such as dealing with large size of arrays, structures having n numbers of students and employees, etc. Thus, whenever you need to allocate memory dynamically, pointers play an important role in it. C language provides some of the functions to allocate and release the memory dynamically. The functions are: malloc() function Allocates an array of num elements each of which size in bytes will be size. calloc() function Allocates an array of num bytes and leaves them uninitialized. realloc() function Reallocates memory extending it up to newsize. 1. The malloc() Function This function is defined in the “stdlib.h” header file. It allocates a block memory of the required size and returns a void pointer. void *malloc (size) The size parameter refers to the block of memory in bytes. To allocate the memory required for a specified data type, you need to use the typecasting operator. For example, the following snippet allocates the memory required to store an int type. int *ptr; ptr = (int * ) malloc (sizeof (int)); Here we need to define a pointer to character without defining how much memory is required and later, based on requirement, we can allocate memory. Example In this example, we use the malloc() function to allocate the required memory to store a string (instead of declaring a char array of a fixed size) − #include <stdio.h> #include <stdlib.h> #include <string.h> int main(){ char *name; name = (char *) malloc(strlen(“TutorialsPoint”)); strcpy(name, “TutorialsPoint”); if(name == NULL) { fprintf(stderr, “Error – unable to allocate required memoryn”); } else { printf(“Name = %sn”, name ); } } Output When the above code is compiled and executed, it produces the following output − Name = TutorialsPoint 2. The calloc() Function The C library function “calloc” (stands for contiguous allocation) allocates the requested memory and returns a pointer to it. void *calloc(n, size); Where “n” is the number of elements to be allocated and “size” is the byte size of each element. The following snippet allocates the memory required to store 10 integer types. int *ptr; ptr = (int *) calloc(25, sizeof(int)); 3. The realloc() Function The realloc() function in C is used to dynamically change the memory allocation of a previously allocated memory. You can increase or decrease the size of an allocated memory block by calling the realloc() function. void *realloc(*ptr, size); The first parameter “ptr” is the pointer to a memory block previously allocated with malloc, calloc or realloc to be reallocated. Dynamic memory allocation technique is extensively used in complex linear and non−linear data structures such as linked lists and trees, which are employed in operating system software. For Passing Arguments as Reference When a function is called by reference, the address of the actual argument variables passed, instead of their values. Passing a pointer to a function has two advantages − First, 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. Second, it also overcomes the limitation of a function in that it can return only one expression. By passing pointers, the effect of processing a function takes place directly at the address. Secondly, more than one value can be returned if we return the pointer of an array or struct variable. Example 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 main(){ /* local variable definition */ int a = 10; int b = 20; printf(“Before swap, value of

C – Properties of Array

C – Properties of Array ”; Previous Next Arrays are a very important data structure in C. Use of array in C program makes it easier to handle large amount of data. Arrays have a number of advantages over singular variables as a result of their number of properties. Most of the important properties of array are a result of its composition − that an array is a collection of values of same data type, and in a continuous block of memory. Array properties may change in the different programming languages. In C programming language, the following are the main properties of arrays: Collection of Same Data Type Contiguous Memory Allocation Fixed Size Length Depends on Type Indexing Pointer Relationship Lower and Upper Bounds Multi-dimensional Array Implementation of Complex Data Structures Let us discuss each property in detail. Collection of Same Data Type All elements of an array must be of the same data type. This ensures consistent access and operations on the data. If an array is declared as follows − int arr[] = {50, 67.55, “hello”, 21}; Compiler issues a warning − initialization of ”int” from ”char *” makes integer from pointer without a cast [-Wint-conversion]| Contiguous Memory Allocation All elements of an array are stored in contiguous memory locations, meaning they occupy a block of memory next to each other. This allows for efficient random access and memory management. Fixed Size The size of an array is fixed at the time of declaration and cannot be changed during the program”s execution. This means you need to know the maximum number of elements you need beforehand. In C, an array cannot have a size defined in terms of a variable. //This is accepted #define SIZE = 10 int arr[SIZE]; //This is also accepted const SIZE = 10; int arr[SIZE]; //This is not accepted int SIZE = 10; int arr[SIZE]; //The size must be an integer. This will give error float num[10.5] = {50, 55, 67, 73, 45, 21, 39, 70, 49, 51}; Length Depends on Type Since an array can store all the elements of same type, the total memory occupied by it depends on the data type. Example #include<stdio.h> int main() { int num[10] = {50, 55, 67, 73, 45, 21, 39, 70, 49, 51}; int size = sizeof(num) / sizeof(int); printf(“element at lower bound num[0]: %d n”, num[0]); printf(“at upper bound: %d byte n”, num[size-1]); printf(“length of int array: %ld n”, sizeof(num)); double nm[10] = {50, 55, 67, 73, 45, 21, 39, 70, 49, 51}; size = sizeof(nm) / sizeof(double); printf(“element at lower bound nm[0]: %f n”, nm[0]); printf(“element at upper bound: %f n”, nm[size-1]); printf(“byte length of double array: %ld n”, sizeof(nm)); return 0; } Output element at lower bound num[0]: 50 at upper bound: 51 byte length of int array: 40 element at lower bound nm[0]: 50.000000 element at upper bound: 51.000000 byte length of double array: 80 Indexing Each element in an array has a unique index, starting from 0. You can access individual elements using their index within square brackets. Usually, array is traversed with a for loop running over its length and using the loop variable as the index. Example #include <stdio.h> int main() { int a[] = {1,2,3,4,5}; int i; for (i=0; i<4; i++){ printf(“a[%d]: %d n”, i, a[i]); } return 0; } Pointer Relationship The name of an array is equivalent to a constant pointer to its first element. This lets you use array names and pointers interchangeably in certain contexts. Example #include <stdio.h> int main() { int num[10] = {50, 55, 67, 73, 45, 21, 39, 70, 49, 51}; printf(“num[0]: %d Address of 0th element: %dn”, num[0], &num[0]); printf(“Address of array: %d”, num); return 0; } Output num[0]: 50 Address of 0th element: 6422000 Address of array: 6422000 Lower and Upper Bounds Each element in an array is identified by an index starting with 0. The lower bound of and array is the index of its first element, which is always 0. The last element in the array size -1 as its index. Example #include <stdio.h> int main() { int num[10] = {50, 55, 67, 73, 45, 21, 39, 70, 49, 51}; int size = sizeof(num) / sizeof(int); printf(“element at lower bound num[0]: %d at upper bound: %d Size of array: %d”, num[0], num[size-1], size); return 0; } Output element at lower bound num[0]: 50 at upper bound: 51 Size of array: 10 Multi-dimensional Array The array is declared with one value of size in square brackets , it is called one dimensional array. In a one dimensional array, each element is identified by its index or subscript. In C, you can declare with more indices to simulate a two, three or multidimensional array. Example For example, following is the example of a two−dimensional array − int a[3][3] = { {1, 2, 3}, {11, 22, 33}, {111, 222, 333}}; You can think of a one dimensional array as a list, and a two dimensional array as a table or a matrix. Theoretically, there is no limit to the number of dimensions of an array, but in practice, two−dimensional arrays are used in design of spreadsheets, databases etc. Implementation of Complex Data Structures We can use an array in the construction of a struct data type to implement data structures such as stack, linked list and trees. Example typedef struct stack { int top; int arr[10]; } Stack; Thus, array

C – Function call by reference

Function Call by Reference in C ”; Previous Next There are two ways in which a function can be called: (a) Call by Value and (b) Call by Reference. In this chapter, we will explain the mechanism of calling a function by reference. Let us start this chapter with a brief overview on “pointers” and the “address operator (&)”. It is important that you learn these two concepts in order to fully understand the mechanism of Call by Reference. The Address Operator (&) in C In C language, a variable is a named memory location. When a variable declared, the compiler allocates a random location in the memory and internally identifies the location with the user-defined name. To fetch the address at which the variable has been created, we use the address (&) operator. Example Take a look at the following example − #include <stdio.h> int main(){ int x = 10; printf(“x: %d Address of x: %d”, x, &x); } Output This will print the value of x and its address − x: 10 Address of x: -1990957196 What is a Pointer in C? A pointer is a variable that stores the address of another variable. To declare a pointer variable, its name is prefixed with the * symbol. The type of the pointer variable and its host variable must be same. The address is assigned with the & operator. The dereference operator (*) is used with the pointer. It fetches the value of a variable whose address is assigned to the pointer. Example The following example demonstrates how referening and dereferencing work in C − #include <stdio.h> int main(){ int x = 10; int *y = &x; printf(“x: %d Address of x: %dn”, x, &x); printf(“Address of y: %d n”, &y); printf(“Value at address in y: %dn”, *y); } Output Run the code and check its output − x: 10 Address of x: -1742755108 Address of y: -1742755104 Value at address in y: 10 How Does Call by Reference Work in C? When a function is called by reference, the address of the actual argument variables passed, instead of their values. Let us define the add() function that receives the references of two variables − int add(int *x, int *y){ int z = *x + *y; return z; } When such a function is called, we pass the address of the actual argument. Example 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 When you run this code, it will produce the following output − Addition: 30 Now let”s understand how this code actually works. The main() function passes the address of a and b to the add() function. The addresses of a and b are assigned to the pointer variables x and y. Now focus on the statement “z = *x + *y;” inside the add() function. Remember that x stores the address of a. The dereference operator in *x and *y fetches the values of a and b respectively, hence z is the addition of a and b in the main() function. Example: Swap Values with Call by Reference Let us understand in more detail how the Call by Reference mechanism works, with the help of the following example that interchanges value of two variables. #include <stdio.h> /* Function definition to swap the values */ /* It receives the reference of two variables whose values are to be swapped */ 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; } /* The main() function has two variables “a” and “b” */ /* Their addresses are passed as arguments to the swap() function. */ 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 run 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 Explanation Assume that the variables a and b in the main() function are allotted locations with the memory address 100 and 200 respectively. As their addresses are passed to x and y (remember that they are pointers), the variables x, y and z in the swap() function are created at addresses 1000, 2000 and 3000 respectively. Since “x” and “y” store the address of “a” and “b”, “x” becomes 100 and “y” becomes 200, as the above figure shows. Inside the swap() function, the first statement “z = *x” causes the value at address in “x” to be stored in “x” (which is 10). Similarly, in the statement “*x = *y;“, the value at the address in “y” (which is 20) is stored in the location whose pointer is “x”. Finally, the statement “*y = z;” assigns the “z” to the

C – Dot (.) Operator

Dot (.) Operator in C ”; Previous Next Dot (.) Operator in C The dot (.) operator in C language is also known as “direction selection member“. It is used to select members of structure and union. The dot (.) operator is a binary operator that requires two operands (structure or union name and member name) and it has the highest operator precedence. The dot (.) operator is useful when you want to access and manipulate the members (variables) of structure and union. Using Dot (.) Operator The dot (.) operator selects the members of the structure and union using the structure and union variable name. Here is the syntax of using the dot (.) operator to access members of a structure or union − var.member; Here, var is a variable of a certain struct or a union type, and member is one of the elements defined while creating the structure or union. Example A new derived data type is defined with struct keyword using the following syntax − struct newtype { type elem1; type elem2; type elem3; … … }; You can then declare a variable of this derived data type as − struct newtype var; To access a certain member, var.elem1; Dot Operator with Structure (struct) As discussed above, the dot (.) operator is used to access and manipulate the members of a structure. Example Let us declare a struct type named book and a struct variable. The following example shows how you can use the dot operator (.) to access the members in the book structure. Take a look at the example − #include <stdio.h> struct book { char title[10]; double price; int pages; }; int main (){ 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); printf(“size of book struct: %d”, sizeof(struct book)); return 0; } Output When you run this code, it will produce the following output − Title: Learn C Price: 675.500000 No of Pages: 325 size of book struct: 32 Dot Operator with Union The union keyword in C also lets you define a derived data type, very much similar to the struct keyword. However, unlike a struct variable, a variable of union type, only one of its members can contain a value at any given time. The dot (.) operator is also used to access and manipulate the members of a union. Example You can also use the dot operator to access union member elements, as shown in this example − #include <stdio.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 : %dn”, data.i); printf( “data.f : %fn”, data.f); printf( “data.str : %sn”, 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 Dot Operator with Nested Structure Nested structures are defined when one of the elements of a struct type is itself a composite representation of one or more types. The dot operator can also be used to access the members of nested structures (and union types also). It can be done in the same way as done for the normal structure. Suppose we have a nested structure as follows − struct struct1 { var1; var2; struct struct2 { var3; var4; } s2; } s1; In this case, the members of s1 are accessed as previously (as s1.var1 and s1.var2), and the members of inner struct are accessed as − s1.s2.var3; Example In this example, we have an employee data type with one of its elements being the date of birth (dob). 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. #include <stdio.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 Run the code and check its output − Name: Kiran Salary: 25000.000000 Date of Birth: 12-5-1990 Accessing the Members Using the Arrow Operator C also has another method to access the members of a struct variable. It can be done with the arrow operator (->) with the help of a pointer to the struct variable. A new derived data type is defined with struct keyword as following syntax − struct newtype { type elem1; type elem2; type elem3; … … }; You can then declare a variable of this derived data type, and its pointer as − struct newtype var; struct newtype *ptr=&var; To access a certain member through the pointer, use the syntax ptr->elem1; Example Take a look at the following example − #include <stdio.h> struct book { char title[10]; double price; int pages; }; int main (){ 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); return 0; } Output When you run this code, it will produce the following output − Title: Learn C Price: 675.500000 No of Pages: 325 Points to Note It may be noted

C – goto Statement

Goto Statement in C ”; Previous Next What is goto Statement in C? The goto statement is used to transfer the program”s control to a defined label within the same function. It is an unconditional jump statement that can transfer control forward or backward. The goto keyword is followed by a label. When executed, the program control is redirected to the statement following the label.If the label points to any of the earlier statements in a code, it constitutes a loop. On the other hand, if the label refers to a further step, it is equivalent to a Jump. goto Statement Syntax The syntax of goto statement is − goto label; . . . . . . label: statement; The label is any valid identifier in C. A label must contain alphanumeric characters along with the underscore symbol (_). As in case of any identifier, the same label cannot be specified more than once in a program. It is always followed by a colon (:) symbol. The statement after this colon is executed when goto redirects the program here. goto Statement Flowchart The following flowchart represents how the goto statement works − goto Statement Examples Example 1 In the following program, the control jumps to a given label which is after the current statement. It prints a given number, before printing the end of the program message. If it is “0”, it jumps over to the printf statement, displaying the message. #include <stdio.h> int main (){ int n = 0; if (n == 0) goto end; printf(“The number is: %d”, n); end: printf (“End of program”); return 0; } Output Run the code and check its output − End of program Example 2 Here is a program to check if a given number is even or odd. Observe how we used the goto statement in this program − #include <stdio.h> int main (){ int i = 11; if (i % 2 == 0){ EVEN: printf(“The number is even n”); goto END; } else{ ODD: printf(“The number is odd n”); } END: printf(“End of program”); return 0; } Output Since the given number is 11, it will produce the following output − The number is odd End of program Change the number and check the output for different numbers. Example 3 If goto appears unconditionally and it jumps backwards, an infinite loop is created. #include <stdio.h> int main (){ START: printf(“Hello World n”); printf(“How are you? n”); goto START; return 0; } Output Run the code and check its output − Hello World How are you? ……. ……. The program prints the two strings continuously until forcibly stopped. Example 4 In this program, we have two goto statements. The second goto statement forms a loop because it makes a backward jump. The other goto statement jumps out of the loop when the condition is reached. #include <stdio.h> int main(){ int i = 0; START: i++; printf(“i: %dn”, i); if (i == 5) goto END; goto START; END: printf(“End of loop”); return 0; } Output Run the code and check its output − i: 1 i: 2 i: 3 i: 4 i: 5 End of loop Example 5 The goto statement is used here to skip all the values of a looping variable that matches with that of others. As a result, all the unique combinations of 1, 2 and 3 are obtained. #include <stdio.h> int main (){ int i, j, k; for(i = 1; i <= 3; i++){ for(j = 1; j <= 3; j++){ if (i == j) goto label1; for (k = 1; k <= 3; k++){ if (k == j || k == i) goto label2; printf(“%d %d %d n”, i,j,k); label2: ; } label1: ; } } return 0; } Output Run the code and check its output − 1 2 3 1 3 2 2 1 3 2 3 1 3 1 2 3 2 1 Avoid Using the goto Statement in C Note that goto in C is considered unstructured, as it allows the program to jump to any location in the code, it can make the code hard to understand, follow, and maintain. Too many goto statements sending the program control back and forth can make the program logic difficult to understand. Noted computer scientist dsger Dijkstra recommended that goto be removed from all the programming languages. He observed that if the program control jumps in the middle of a loop, it may yield unpredictable behaviour. The goto statements can be used to create programs that have multiple entry and exit points, which can make it difficult to track the flow of control of the program. Dijkstra”s strong observations against the use of goto statement have been influential, as many mainstream languages do not support goto statements. However, it is still available in some languages, such as C and C++. In general, it is best to avoid using goto statements in C. You can instead effectively use if-else statements, loops and loop controls, function and subroutine calls, and try-catch-throw statements. Use goto if and only if these alternatives don’t fulfil the needs of your algorithm. c_loops.htm Print Page Previous Next Advertisements ”;

C – Pointer vs Array

Pointer vs Array in C ”; Previous Next Arrays and Pointers are two important language constructs in C, associated with each other in many ways. In many cases, the tasks that you perform with a pointer can also be performed with the help of an array. However, there are certain conceptual differences between arrays and pointers. Read this chapter to understand their differences and comparative advantages and disadvantages. Arrays in C In a C program, an array is an indexed collection of elements of similar type, stored in adjacent memory locations. To declare an array, we use the following syntax − data_type arr_name [size]; The size should be a non-negative integer. For example − int arr[5]; The array can be initialized along with the declaration, with the elements given as a comma-separated list inside the curly brackets. Mentioning its size is optional. int arr[] = {1, 2, 3, 4, 5}; Each element in an array is characterized by a unique integral index, starting from “0”. In C language, the lower bound of an array is always “0” and the upper bound is “size – 1”. Example of an Array The following example shows how you can traverse an array with indexed subscripts − #include <stdio.h> int main (){ /* an array with 5 elements */ int arr[5] = {10, 20, 30, 40, 50}; int i; /* output each array element”s value */ printf(“Array values with subscripts: n”); for(i = 0; i < 5; i++){ printf(“arr[%d]: %dn”, i, arr[i]); } return 0; } Output When you run this code, it will produce the following output − Array values with subscripts: arr[0]: 10 arr[1]: 20 arr[2]: 30 arr[3]: 40 arr[4]: 50 Pointers in C C allows you to access the memory location of a variable that has been randomly allocated by the compiler. The address−of operator (&) returns the address of the variable. A variable that stores the address of another variable is called a pointer. The type of the pointer must be the same as the one whose address it stores. To differentiate from the target variable type, the name of the pointer is prefixed with an asterisk (*). If we have an int variable, its pointer is declared as “int *”. int x = 5; int *y = &a; Note: In case of an array, the address of its 0th element is assigned to the pointer. int arr[] = {1, 2, 3, 4, 5}; int *ptr = &arr[0]; In fact, the name of the array itself resolves to the address of the 0th element. Hence, we can as well write − int *ptr = arr; Since the elements of an array are placed in adjacent memory locations and the address of each subscript increments by 4 (in case of an int array), we can use this feature to traverse the array elements with the help of pointer as well. Example of a Pointer The following example shows how you can traverse an array with a pointer − #include <stdio.h> int main (){ /* an array with 5 elements */ int arr[5] = {10, 20, 30, 40, 50}; int *x = arr; int i; /* output each array element”s value */ printf(“Array values with pointer: n”); for(i = 0; i < 5; i++) { printf(“arr[%d]: %dn”, i, *(x+i)); } return 0; } Output Run the code and check its output − Array values with pointer arr[0]: 10 arr[1]: 20 arr[2]: 30 arr[3]: 40 arr[4]: 50 Difference between Arrays and Pointers in C The following table highlights the important differences between arrays and pointers − Array Pointer It stores the elements of a homogeneous data type in adjacent memory locations. It stores the address of a variable, or an array An array is defined as a collection of similar datatypes. A pointer is a variable that stores address of another variable. The number of variables that can be stored is decided by the size of the array. A pointer can store the address of only a single variable. The initialization of arrays can be done while defining them. Pointers cannot be initialized while defining them. The nature of arrays is static. The nature of pointers is dynamic. Arrays cannot be resized according to the user”s requirements. Pointers can be resized at any point in time. The allocation of an array is done at compile time. The allocation of the pointer is done at run time. Print Page Previous Next Advertisements ”;