C Unit 5
C Unit 5
Understanding pointers
Pointer is a variable, which holds the address of other variable of the same data type.It is a
derived data type. The pointer are used to access memory and manipulate the address.
The computer memory consists of storage cells. Each cell has one byte of memory space. Each
byte is uniquely identified by a sequence number, called as address.
Syntax:
datatype *pointer_variable;
Where,
Examples:
Note:
All globally declared pointers are called as Null pointers. The value assigned to them in
zero.
All locally declared uninitialized pointers are called as Dangling pointer. The value
assigned to them is unpredictable.
Where,
Example:
? ?
Ptr
Contains Garbage
Value
While declaring/initializing the pointer variable, * indicates that the variable is a pointer.
The address of any variable is given by preceding the variable name with Ampersand .
Normal variable stores the value, but the pointer variable stores the address of a variable.
The declaration int *a doesn’t mean that a is going to contain an integer value. It means
that a is going to contain the address of a variable storing integer value.
To access the value of a certain address stored by a pointer variable * is used. Here, the *
indicates pointer, which read as ‘value at address’.
Accessing address and value of variables using pointers:
As we know that a pointer is a special type of variable that is used to store the memory address of
another variable. A normal variable contains the value of any type like int. char, float etc. while a pointer
variable contains the memory address of another variable.
Here, we are going to learn how can we access the value of another variable using the pointer
variable?
Steps:
1. Declare a normal variable of any data type, assign the value.
2. Declare a pointer variable with the same type as the normal variable.
3. Initialize the pointer variable with the address of normal variable.
4. Access the value of the variable by using asterisk (*) – it is known as dereference
operator.
Ecample: Here, we have declared a normal integer variable called num and finally getting the value of
num using pointer variable ptr.
#include<stdio.h>
void main(void)
{
//normal variable
int num = 100;
// pointer variable
Int *ptr;
// pointer variable
ptr = #
//printing the value of num by using the pointer ptr
Printf(“value of num =%d\n”, *ptr);
getch()
}
POINTERS AND ARRAYS
In C programming, when we declare an array the compiler allocate the required amount of
memory and also creates a constant pointer with array name and stores the base address of that
pointer in it. The address of the first element of an array is called as base address of that array.
The array name itself acts as a pointer to the first element of that array.
Consider the following example of an array declaration.
int X[10];
For the above declaration, the compiler allocates 12 bytes of memory and the address of
first memory location (i.e., X[0]) is stored in a constant pointer called X . That means in the
above
Example, X is a pointer to X[0].
The memory representation in as follows
Just the array name indicates the starting address of the array. In other words X means the
address of the 1st element of the array (&X[0])
&X[1] and (X+1) are pointed to same memory block 2002. Just ‘X referring the address 2000
and (X+0) referring the same address is called as “base address”. Adding 1 to an integer Pointer,
will actually increase the pointer value by 2, So that it points to the next memory location. The address of
each element can be obtained as follows,
Where,
The scale factor depends on the data type of tht array. That means integer has 2 bytes, character has1
byte, float has 4 byte and double has 8 bytes.
Note:
Program to find the sum f six numbers with arrays and pointers.
#include<stdio.h>
Void main()
{ Output:
Printf(“Enter 6 numbers:\n”); 2
For(i=0;i<6;++i) 3
4
{
5
Scanf(“%d”,(class+i));
3
Sum +-*(class+i);
4
}
Sum=21
Printf(“Sum=%d”,sum); //(class+i) is equivalent to &class[i]
C calloc() method
1. “calloc” or “contiguous allocation” method in C is used to dynamically allocate the specified number
of blocks of memory of the specified type. it is very much similar to malloc() but has two different points
and these are:
2. It initializes each block with a default value ‘0’.
3. It has two parameters or arguments as compare to malloc().
Syntax of calloc() in C
ptr = (cast-type*)calloc(n, element-size);
here, n is the no. of elements and element-size is the size of each element.
For Example:
ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for 25 elements each with the size of the float.
C free() method
“free” method in C is used to dynamically de-allocate the memory. The memory allocated using functions
malloc() and calloc() is not de-allocated on their own. Hence the free() method is used, whenever the
dynamic memory allocation takes place. It helps to reduce wastage of memory by freeing it.
Syntax of free() in C
free(ptr);
C realloc() method
“realloc” or “re-allocation” method in C is used to dynamically change the memory allocation of a
previously allocated memory. In other words, if the memory previously allocated with the help of malloc or
calloc is insufficient, realloc can be used to dynamically re-allocate memory. re-allocation of memory
maintains the already present value and new blocks will be initialized with the default garbage value.
Syntax of realloc() in C
ptr = realloc(ptr, newSize);
where ptr is reallocated with new size 'newSize'.
The file handling functions are declared in the <stdio.h> header, so you need to include this header
at the beginning of your program.
c
Copy code
#include <stdio.h>
A file pointer of type FILE* is used to handle file operations. You declare a file pointer like this:
c
Copy code
FILE *file;
Use the fopen function to open a file. The fopen function returns a pointer to a FILE structure if
successful, or NULL if the file could not be opened. The syntax is:
c
Copy code
FILE *fopen(const char *filename, const char *mode);
Common Modes:
c
Copy code
#include <stdio.h>
int main() {
FILE *file;
// Open the file for writing
file = fopen("example.txt", "w");
return 0;
}
c
Copy code
#include <stdio.h>
int main() {
FILE *file;
char buffer[100];
return 0;
}
4. Error Handling
Always check if fopen returns NULL. This indicates that the file could not be opened. Use perror or
fprintf with strerror(errno) to print a descriptive error message.
After performing file operations, close the file using fclose to free up resources and ensure that
any buffered data is written to the file.
c
Copy code
if (fclose(file) != 0) {
perror("Error closing file");
}
Command Line Arguments
The most important function of C is the main() function. It is mostly defined with a return type of int and
without parameters.
int main() {
...
}
We can also give command-line arguments in C. Command-line arguments are the values given after the
name of the program in the command-line shell of Operating Systems. Command-line arguments are
handled by the main() function of a C program.
To pass command-line arguments, we typically define main() with two arguments: the first argument is
the number of command-line arguments and the second is a list of command-line arguments.
Syntax
int main(int argc, char *argv[]) { /* ... */ }
or
int main(int argc, char **argv) { /* ... */ }
argc (ARGument Count) is an integer variable that stores the number of command-line arguments
passed by the user including the name of the program. So if we pass a value to a program, the value of
argc would be 2 (one for argument and one for program name)
The value of argc should be non-negative.
argv (ARGument Vector) is an array of character pointers listing all the arguments.
If argc is greater than zero, the array elements from argv[0] to argv[argc-1] will contain pointers to
strings.
argv[0] is the name of the program , After that till argv[argc-1] every element is command -line
arguments.
For better understanding run this code on your Linux machine.
Example
The below example illustrates the printing of command line arguments.
// C program named mainreturn.c to demonstrate the working
// of command line arguement
#include <stdio.h>