The fputc function and putc macro are used to write a character to an output stream. Their prototypes are given below. [Read more…] about C program to fputc Function and the putc Macro
C program to count the number of characters, words and lines in a text file
Let us use a while loop in conjunction with the getc macro to read a text file character by character as explained in Program. The counting of characters and lines is very straight forward, the code for which is given below. [Read more…] about C program to count the number of characters, words and lines in a text file
The fclose Function in C
When I/O operations on a file are complete, we must close the file using the fclose function. The prototype of this function is as follows: [Read more…] about The fclose Function in C
C Program to read and print info of a person
The program given below reads the information about a person and prints it on the screen. It uses a structure containing a pointer member name to represent the information about a person. Note that the program uses the dstr_read function. [Read more…] about C Program to read and print info of a person
C Program determine the frequency of words in a given string
A program to determine the number of words and average word length is given in Program. It uses the strtok function to separate the words in a given string. The program given below uses the same technique to separate the words in a given string and determine and print the frequency of these words. [Read more…] about C Program determine the frequency of words in a given string
Structure Containing Arrays in C
The C language allows an array to be used as a structure member. This enables us to group related structure members and is also useful for declaring character strings as structure members. This section explains how we can effectively use such structures. This includes [Read more…] about Structure Containing Arrays in C
C Program using structures and functions, to compare two dates
Consider the problem of comparison of two valid dates d1 and d2. There are three possible outcomes of this comparison: d1 == d2 (dates are equal), d1 > d2 (date d1 is greater, i.e., occurs after d2) and d1 < d2(date d1 is smaller, i.e., occurs before d2). Let us write a function that accepts two dates as structures dl and d2 of type struct date and returns 0 if the dates are equal, 1 if d1 is later than d2 and -1 if date dl is earlier than d2. [Read more…] about C Program using structures and functions, to compare two dates
C Program to add of two complex numbers
Let us use structure complex to represent a complex number and write a simple program containing only the main function. Thus, we can define structure complex either in the main function or before it as a global definition. [Read more…] about C Program to add of two complex numbers
C Program Reads a string using dynamic memory allocation for strings
The function dstr_read given below reads a string from the keyboard into array buf, stores it in dynamically allocated memory and returns a pointer to it. [Read more…] about C Program Reads a string using dynamic memory allocation for strings
C program to Average Character Per Word in a String
We may want to know the number of words in a given string and the average word length. The English text contains words (i. e., sequences of letters) separated by spaces, newlines and punctuation marks such as period, comma, semicolon, colon, quotation marks, exclamation, question mark, etc. It is quite a difficult job to separate the words from these punctuation marks. However, this task is greatly simplified when we use the powerful strtok function provided in the standard C library. The program given below determines the number of words in a given string and the average word length. [Read more…] about C program to Average Character Per Word in a String
C program to separate the words in a given string
Let us write function str words to accept a string and separate the words in it. The number of words in a given string as well as the number of characters in each word are not known before hand. To keep the code simple, let us assume that the given string contains at the most MAX WORD words and each word in turn contains at the most MAX_ CHAR characters. Thus, the function str words can return the words in the given string in a two-dimensional array of size MAX_ WORD x MAX_CHAR of type char, as shown in fig. [Read more…] about C program to separate the words in a given string
C Program Swap String Using Strcpy Function
The function accepts two strings, str1 and str2, as parameters of type char * and exchanges their contents. Note that the strcpy function is used to copy the strings and a local character array is used to store string strl temporarily. This function can be called from the main function to exchange strings as shown below. [Read more…] about C Program Swap String Using Strcpy Function
strcmp function in C
A typical call to the strcmp function take the following form: [Read more…] about strcmp function in C
Two-Dimensional Arrays Using a Pointer to Pointer
Since a pointer to type T is analogous to an array of type T, a pointer to a pointer (T**) is analogous to an array of type T*, i. e., an array of pointers to type T. Each element in this array of pointers can be used further to point to an array of type T. Thus, a pointer to a pointer can be used to represent two-dimensional arrays, as illustrated in Fig.
Observe that we have a lot of flexibility in allocating memory for two-dimensional arrays. Thus, we can allocate a rectangular matrix (Fig a), a lower/upper triangular matrix (Fig b) and a ragged matrix in which each row can have different number of elements (Fig c). The use of a pointer to a pointer in conjunction with dynamic memory allocation is advantageous over a static matrix as it allows the allocation of a two-dimensional array of desired size and shape, avoiding wastage of memory.
Note that when a pointer to a pointer is declared, the memory is allocated only for the pointer variable. The memory for the pointer array and the two-dimensional array elements is usually allocated separately using dynamic memory allocation functions, namely, malloc or calloc.
A simplified function imat_alloc given below allocates a regular integer matrix of size m x n to variable tmp of type int ** and returns this pointer to the calling function
int **imat_alloc(int m, int n)
{
int i;
int **tmp = (int**) malloc(m * sizeof(int *));
for(i = 0; i < m; i++)
tmp[i] = (int*) malloc(n * sizeof(int));
return tmp;
}
Note that the function return type is a pointer to a pointer to int, i.e., int ** and the function returns a value of correct type (as tmp is of type int ** ). First, malloc allocates memory form pointers (i. e., m* sizeof (int *)) and assigns the address of this block, after typecasting to int **, to variable tmp. Then a for loop is used to allocate memory for each row. The malloc function now allocates memory for n integers (i.e., n * sizeof (inti) and assigns the address of this block, after typecasting to int *, to the ith pointer tmp[i] . Finally, the value of tmp is returned.
As you have probably noticed, the error checking code has been omitted in imat_alloc function to keep the things simple and focus on memory allocation logic. Although this is okay for small programs, we should include the error handling code in actual applications. The modified function is given below.
/* allocate the memory for a dynamic matrix */
int **imat_alloc(int m, int n)
{
int i;
/* first allocate memory for pointer array */
int **tmp = (int**) malloc(m * sizeof(int *));
if (tmp == NULL) {
printf(“Error: Out of memory …\n”);
exit(1);
}
/* allocate memory for matrix rows */
for(i = 0; i < m; i++) {
tmp[i] = (int*) malloc(n * sizeof(int));
if (tmp[i] ==NULL) {
printf (“Error: Out of memory …\n”);
exit (1);
}
}
return tmp;
}
This function can be called from any function to allocate a matrix as shown below.
int **a;
a= imat_alloc(m, n);
Note that now we cannot simply use the free function (as in free (a))to free the memory allocated to a matrix as it will only free the memory allocated to the pointer array. The function imat_free to free an integer matrix is given below. It accepts two parameters: a pointer to the matrix and the number of rows. It first uses a for loop to free the memory allocated to matrix rows and then frees the memory allocated to the pointer array.
void imat_free(int **a, int m)
{
int i;
/* free the memory allocated to matrix rows */
for (i = 0; i < m; i++)
free(a[i]);
free(a); /* free the memory allocated to pointer array */
}
Illustrates pointers to one- and two-dimensional arrays
#include <stdio.h>
void main()
{
int i, j , k;
int Array[2] [3] = {2,3,4,5,6,7 };
int (*pArray) [3] = Array ;
int Bray[4] = {10, 11, 12, 13};
int *pBray = Bray;
for ( k=0 ; k<4; k++)
printf("Bray[%d] = %d\n", k, *(pBray + k ));
for ( i=0 ; i<2; i++)
for ( j =0; j<3; j++)
{
printf("Array[%d] [%d] = %d ", i, j, *(*(Array +i)+j));
printf(",\tpArray[%d] [%d] = %d\n", i, j, *(*(pArray +i)+j));
}
}
What is Dynamic Vectors in C
As we know, a pointer to type T is analogous to an array of type T.A pointer can be used to represent a vector, as illustrated in Fig. When a pointer is declared, the memory is allocated only for the pointer variable. The memory for the array elements is usually allocated separately using dynamic memory allocation functions, namely, malloc or calloc. [Read more…] about What is Dynamic Vectors in C
What is Dynamic Arrays in C
An array is a powerful and easy-to-use data structure provided in the C language. We know that arrays provide easy access to their elements and entire arrays can be manipulated easily using loops. However, there are some drawbacks/limitations of arrays: [Read more…] about What is Dynamic Arrays in C
Dynamic Memory Management in C
When a C program is compiled, the compiler allocates memory to store different data elements such as constants, variables (including pointer variables), arrays and structures. This is referred to as compile-time or static memory allocation. There are several limitations in such static memory allocation: [Read more…] about Dynamic Memory Management in C
Pointer to a Pointer in C
We have defined a pointer as a variable which keeps the address of another variable. Since pointer is also a variable and is allocated memory space in which its value is stored, so we can have another variable which keeps the address of the pointer. That would be a pointer to a pointer. Such a pointer to a pointer is depicted in Fig, in which pointer ppa points to pointer pa, which in turn points to variable a. These pointers can be initialized as shown below.
int a, *pa, **ppa;
pa = &a; /* pointer pa points to variable a */
ppa = &pa; /* pointer ppa points to pointer pa */
These declarations can be alternatively written in a more readable form as
int a;
int *pa = &a;
int **ppa = &pa;
Now we can use pointer ppa to access the value of variable a. As we know, the expression *ppa gives the value pointed by pointer to ppa which is the value of pointer pa (i. e., the address of variable a). Thus, to access the value of variable a, we have to dereference pointer ppa once more, as in **ppa. Thus, the expression **ppa = 10 assigns value 10 to variable a and ++ **ppa increments its value. Note that the variable a can be accessed using pointer pa as well. Thus, we can also set variable a to 10 using expression *pa= 10.
Note that we can extend this concept further. The declaration
int ***pppa = &ppa;
declares pppa as a pointer to a pointer to a pointer to variable a and initializes it to point to variable ppa declared earlier. This pointer is illustrated in Fig. To access variable a using pointer pppa, we must dereference it three times. Thus, ***pppa = 1o assigns value 10 to variable a.
You might be wondering what is the use of such pointers to other pointers. However, as we will see, they are used to create dynamic multidimensional arrays. For example, a pointer to pointer is used to create a dynamic matrix, and a pointer to a pointer to a pointer is used to create a dynamic three-dimensional array.
illustrates pointer to a pointer and also pointer to pointer to a pointer
int main ()
{
int m = 80 ; // int variable
int* pm= &m ; // pointer to int variable
int** ppm= ± // pointer to pointer to variable
int*** pppm = &ppm; // pointer to pointer to pointer
clrscr();
printf("Variable m = %d\tAddress of m %u\n", m, &m);
printf("Pointer pm= %u\n", pm);
printf("Address of pm= %u\n", &pm);
printf("Pointer to pointer ppm= %u\n",ppm);
printf("Address of ppm= %u\n",&ppm);
printf("Pointer to pointer to pointer pppm = %u\n", pppm);
printf("Address of pppm = %u\n", &pppm);
printf("Now by dereference, ppm= *pppm = %u\n" ,*pppm);
printf("Now by dereference, pm =*ppm= %u\n" ,*ppm);
printf("Value of m = *pm= %d\n" ,*pm);
printf("Value of m = **ppm= %d\n", **ppm);
printf("Value of m = ***pppm = %d\n", ***pppm);
return 0;
}
The expected output is as given below.
Multidimensional Arrays and Pointers in C
For example, consider the declarations of a three-dimensional array of size 2 x 3 x 4 given below.
int a[2][3][4];
We can interpret a as an array having three elements each of which is a matrix of size 3 x 4. Thus, contiguous memory is allocated for three matrices a [0], a [1] and a [2].
As we know, array name a is a pointer to its beginning. Actually, it is a pointer to a matrix of size 3 x 4, i. e., (*a) [3] [4]. We can access the ijkth element of this matrix using pointer notation as * (* (* (a+ i) +j )+k) . We can pass this array to a function and access its elements using pointer notation as illustrated in the iarr3d _print function given below.
void iarr3d_print (int (*a) [3] [4], int; m, int n, int p)
{
int i, j, k;
int *pa = **a; /* init int pointer to point to a[0] [0] [0] */
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
for (k = 0; k < p; k++)
printf(“%2d “, *pa++); /* access elem & incr ptr */
printf(“\n”);
}
printf(“\n\n”);
}
}
Note that the pointer pa is initialized to **a. As a is a pointer to array a [oJ of size 3 x 4, *a is a pointer to vector a [0] [0] having four elements and dereferencing it once more as **a, we get a pointer to element a [0] [0] [0]. Alternatively, we can write this initialization as
int *pa= (int*) a; /* init int pointer to point to a[0] [0] [0] */
Accessing Matrix Elements by Using Array Name as a Pointer
As we know, the expression x [i] to access the ith element of vector x can be equivalently written using pointer notation as * (x+i) . Thus, the expression a [i] [j] to access the ijth element of matrix a can be equivalently written as * (*(a+i) +j). Observe that this expression is obtained by applying twice the construct used for a vector. The address of a [i][j] is thus given as * (a+i) +j. These results are summarized below. [Read more…] about Accessing Matrix Elements by Using Array Name as a Pointer
Return pointer from functions in C
So far we have studied functions that either return a value or have a void return type. A function can also return a pointer to a data item of any type. However, we must be careful while returning pointers from a function. A common mistake would be to return a pointer to a local variable or value parameter in that function as they are destroyed when control returns to the calling function.
In situations where we have to return a pointer to a local variable, we must allocate the memory for such variables using dynamic memory management techniques, i.e., using malloc, calloc and realloc standard· library functions. Such dynamically allocated variables last till the end of program execution. Thus, the memory allocated using these functions is not destroyed when the control returns to the calling functions.
Example of Returning a Pointer from a Function
Consider that we wish to write a function that accepts two integer numbers and returns a pointer to the smaller number. The function bad_pmin1 given below has two value parameters (a and b) and return type of pointer to int. Within this function, the smaller number is first determined in variable small whose address is then returned as expected. However, this implementation is incorrect as it returns the address of a local variable. ·
int *bad_pminl(int a, int b) /* INCORRECT FUNCTION */
{
int small = (a < b) ? a : b;
return &small; /* Wrong: can’t return addr of local variable */
}
The function bad_pmin2 given below is also incorrect as it returns the address of one of the function parameters which, as we know, is local to the function.
int main()
{
short int a = 6;
float x = 1.23;
printf(“short int : %4hd Binary: “, a);
print_binary((unsigned char*) &a, sizeof(a));
printf(“\nfloat : %0.2f Binary: “, x);
print_binary((unsigned char*)_ &x, sizeof(x));
return 0;
}
Observe how the address of the variable to be printed is typecast to unsigned char *. The program output is given below.
short int : 6 Binary: 00000000 00000110
float : 1.23 Binary: 00111111 10011101 01110000 10100100
Typecast and sizeof Operators in C
We can use typecast operator to convert the type of value returned by a pointer dereference expression to another suitable type. For example, if pa is a pointer to a variable a of type int, we can use typecast as (double) *pa to convert the integer value of *pa to type double.
The C language also allows us to use typecast to convert the type of a pointer, as in (char *) pa. This converts the pointer pa, which is assumed to be a pointer to int, to char *, i. e., a character pointer. Such typecasts are essential and are commonly used while dealing with void pointers. However, it should be used very carefully in other situations as it may lead to erroneous situations. For example, the expression *pa interprets the contents of two (or four) consecutive memory locations pointed to by pointer pa as an integer, whereas the expression * ( (char *) pa) interprets the contents of only one byte pointed to by pa, i. e., some part of integer value, as a character. Nevertheless, there are situations where this kind of conversion is useful, as illustrated in Example.
The sizeof operator, when used with a pointer variable, as in sizeof (pa), gives us the size of a pointer variable, i. e., memory required for its storage in bytes.
Example of function to print binary representation of numbers
Consider that we wish to print binary representations of numbers of different data types (int, short int, float, long double, etc.). One approach to do this is to write a separate function for each data type. However, this is tedious and time-consuming. Instead, we can write a single function named print_binary the as shown below.
void print_binary(unsigned char *pc, int n)
{
int i;
for(i = n – 1; i >= O; i–) /* process bytes from MSB to LSB */
print_char_bits(pc[i]); /* print a byte in binary */
}
To handle different data types and sizes, this function accepts an unsigned character pointer to the variable to be printed and its size in bytes. The for loop is set up to process individual bytes starting with the most significant byte (which is the last byte on most computers as the numbers are stored starting with the least significant byte). The bit pattern of each byte is printed by calling the print_ char_ bits function given below.
void print_char_bits(unsigned char c)
{
int i;
unsigned char mask= Ox80; /* i.e. mask = 10000000 (binary) */
for(i = 7; i >= 0; i–)
{
printf(“%c”, (c & mask? ‘1’: ‘0’)); /*print bit at position i*/
mask >>= 1; /* shift ‘1’ in mask to right side */
}
printf (” “) ;
}
This function accepts a byte as an unsigned character and uses a for loop to process individual bits in a character starting with the most significant bit (i. e., bit 7). A mask is used to separate individual bits. It is initialized to Ox80 (i.e., 1000 00002) before the loop and in each iteration, .the bit pattern is shifted to the right by one position. The bit-wise and (&) operator is used along with the conditional operator to print a bit as
printf(“%c”, (c & mask? ‘1’ : ‘0’)); /*print bit at position i */
Note that to simplify the code, we can eliminate variable i and use variable mask as the loop variable as shown below.
void print_char_bits(unsigned char c)
{
unsigned char mask;
for(mask = Ox80; mask> 0; mask>>= 1) /* process bits MSB to LSB */
printf(“%c”, (c & mask? ‘1’ : ‘0’)); /*print current bit*/
printf(” “);
}
The main function used to print the binary representations of two numbers (of type short int and float) is given below.
int main()
{
short int a = 6;
float x = 1.23;
printf (“short int : %4hd Binary: “, a);
print_binary((unsigned char*) &a, sizeof(a));
printf(“\nfloat : %0.2f Binary: “, x);
print_binary( (unsigned char *).&x, sizeof(x));
return O;
}
Observe how the address of the variable to be printed is typecast to unsigned char *.The program output is given below.
short int : 6 Binary: 00000000 00000110
float : 1.23 Binary: 00111111 10011101 01110000 10100100
Vectors and Pointers in C
We have studied that an array is a powerful built-in data structure in the C language. It is a collection of data items of the same type stored in consecutive memory locations. An element of an array can be accessed using subscript notation, as in a [i ] , b [ i ] [ j ] , etc. Also, we can process entire arrays using loops and pass them to functions. [Read more…] about Vectors and Pointers in C
Function call by reference in C
We know that when a function is called, the parameters are passed to it by value, i.e., the values of arguments in a function call are copied to the parameters of the called function. Since a function parameter is a copy of the argument variable and is local to the function, any change in its value in the body of the function modifies only the local copy and not the corresponding argument in the calling function. [Read more…] about Function call by reference in C
How to Pointer Assignment and Initialization in C
When we declare a pointer, it does not point to any specific variable. We must initialize it to point to the desired variable. This is achieved by assigning the address of that variable to the pointer variable, as shown below. [Read more…] about How to Pointer Assignment and Initialization in C
Difference Address (&) and Dereference Operator (*)
To manipulate data using pointers, the C language provides two operators: address (&) and dereference (*). These are unary prefix operators. Their precedence is the same as other unary operators which is higher than multiplicative operators.
The address operator (&) can be used with an lvalue, such as a variable, as in &var. This expression yields the address of variable var, i.e., a pointer to it. Note that the address operator cannot be used with constants and non-lvalue expressions. Thus, the expressions &100,&(a+5) and &’X’ are invalid. If the type of variable var is T, the expression &var returns a value of type T *,i.e., a pointer to type T. As mentioned earlier, we need not know the exact address where a particular variable is stored in memory. We can use the addressoperator to obtain its address, whatever it may be. This address can be assigned to a pointervariable of appropriate type so that the pointer points to that variable.
The dereference operator (*) is a unary prefix operator that can be used with any pointer variable, as in *ptr_var. This expression yields the value of the variable pointed at by that pointer. Although the symbol for the dereference operator is the same as that of the multiplication operator, its use is unambiguous from the context as the latter is a binary infix operator used, as in expr1 * expr2.
How are pointer variables declared
The C language permits a pointer to be declared for any data type. The declaration of a pointer variable takes the following general form: [Read more…] about How are pointer variables declared
Multidimensional Arrays in C
C language permits the use of multidimensional arrays. It is easy to visualize arrays up to three dimensions. However, we may have difficulty in visualizing a four, five or in general, an n-dimensional array. [Read more…] about Multidimensional Arrays in C
Two-dimensional Arrays or Matrices in C
A two-dimensional array (commonly called a matrix) consists of elements of the same type arranged in rows and columns. The rows and columns of a matrix are numbered starting from 0. Thus, for an array of size rows x cols, the row subscripts are in the range 0 to rows – 1 and the column subscripts are in the range 0 to cols – 1. [Read more…] about Two-dimensional Arrays or Matrices in C
Global Arrays in C
As in case of scalar variables, we can also use external or global arrays in a program, i. e., the arrays which are defined outside any function. These arrays have global scope. [Read more…] about Global Arrays in C