0% found this document useful (0 votes)
11 views12 pages

C Unit 5

best notes

Uploaded by

Amogh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views12 pages

C Unit 5

best notes

Uploaded by

Amogh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Pointers– Memory Allocation and File management

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.

Declaring a pointer variable

Syntax:

datatype *pointer_variable;

Where,

datatype can be int, float, char, double, etc

Pointer_variable can be any valid identifier

* Indicates to the variable of type pointer.

Examples:

int *p; // p is an integer pointer or p is a pointer to integer data type

float *q; // q is a floating point pointer

char *r; // r is a character type pointer

double *s; // s is pointer to double type pointer

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.

Initialization of C Pointer variable

Pointer Initialization is the process of assigning address of a variable to a pointer variable. It


contains the address of a variable of the same data type. In C language address operator & in
used to determine the address of a variable. The & (immediately preceding a variable name)
returns the address of the variable associated with it.
Syntax : ptr-var = & var;

Where,

Ptr-va is a pointer variable,

& is a address of the variable

Var is the normal variable.

Example:

Int a=10; // normal variable

Int *p; // pointer variable

P = & a; // assign address of the variable ’a’ to pointer variable p.

Normal variable a p p pointer variable


10 1000 Values

1000 2000 Address

 Pointer variable always points to the variable of same data type.


Example:
float a;
int *ptr = &a; //ERROR, type mismatch
 While declaring a pointer variable, if not assigned to any address, then it contains garbage value.
Therefore, it is recommended to assign a NULL value to it.

? ?

Ptr

Contains Garbage

Value

 A pointer is assigned a NULL value is cal;led a NULL pointer in C.

Points to remember while using pointers

 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 = &num;
//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,

Array Element Address pointer Representation Example

&X[0] (X+0) (2000+0*2)

&X[1] (X+1) (2000+1*2)

&[4] (X+4) (2000+4*2)

Where,

2000 is the Base or starting address of the array in above example

0,1,2,3,...9 are the array subscripts.


2 is the scale factor.

In general &X[0] can be written as (X+i) where i=0,1,2......n.

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:

1. An array name is a constant pointer.


2. The array name is used to access the address and value of all the elements of that array.
3. Science array name is a constant pointer we can’t modify its value.

Program to find the sum f six numbers with arrays and pointers.

#include<stdio.h>

Void main()

{ Output:

Int i,class[6],sum=0; Enter 6 numbers:

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]

Getch(); //*(class+i) is equivalent to class[i]

Dynamic Memory Allocation in C using malloc(), calloc(),free() and


realloc()
Since C is a structured language, it has some fixed rules for programming. One of them includes changing
the size of an array. An array is a collection of items stored at contiguous memory locations.
As can be seen, the length (size) of the array above is 9. But what if there is a requirement to change this
length (size)? For example,
 If there is a situation where only 5 elements are needed to be entered in this array. In this case, the
remaining 4 indices are just wasting memory in this array. So there is a requirement to lessen the length
(size) of the array from 9 to 5.
 Take another situation. In this, there is an array of 9 elements with all 9 indices filled. But there is a need
to enter 3 more elements in this array. In this case, 3 indices more are required. So the length (size) of the
array needs to be changed from 9 to 12.
This procedure is referred to as Dynamic Memory Allocation in C.
Therefore, C Dynamic Memory Allocation can be defined as a procedure in which the size of a data
structure (like Array) is changed during the runtime.
C provides some functions to achieve these tasks. There are 4 library functions provided by C defined
under <stdlib.h> header file to facilitate dynamic memory allocation in C programming. They are:
1. malloc()
2. calloc()
3. free()
4. realloc()

Let’s look at each of them in greater detail.


C malloc() method
The “malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of
memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any
form. It doesn’t Initialize memory at execution time so that it has initialized each block with the default
garbage value initially.
Syntax of malloc() in C
ptr = (cast-type*) malloc(byte-size)
For Example:
ptr = (int*) malloc(100 * sizeof(int));
Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And, the pointer ptr holds
the address of the first byte in the allocated memory.
If space is insufficient, allocation fails and returns a NULL pointer.

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.

If space is insufficient, allocation fails and returns a NULL pointer.

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'.

If space is insufficient, allocation fails and returns a NULL pointer.


To define and open a file in C, you need to follow these steps, which include defining a file pointer,
opening the file with a specific mode, handling errors, and eventually closing the file. Here's a
comprehensive guide to each step:

1. Include the Required Header

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>

2. Define a File Pointer

A file pointer of type FILE* is used to handle file operations. You declare a file pointer like this:

c
Copy code
FILE *file;

3. Open the 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);

 filename: The name of the file you want to open.


 mode: The mode in which to open the file.

Common Modes:

 "r": Open for reading. The file must exist.


 "w": Open for writing. Creates a new file or truncates an existing file.
 "a": Open for appending. Creates a new file if it doesn't exist.
 "r+": Open for both reading and writing. The file must exist.
 "w+": Open for both reading and writing. Creates a new file or truncates an existing file.
 "a+": Open for both reading and appending. Creates a new file if it doesn't exist.

Example: Opening a File for Writing

c
Copy code
#include <stdio.h>

int main() {
FILE *file;
// Open the file for writing
file = fopen("example.txt", "w");

// Check if the file was successfully opened


if (file == NULL) {
perror("Error opening file");
return 1;
}

// File operations go here

// Close the file


fclose(file);

return 0;
}

Example: Opening a File for Reading

c
Copy code
#include <stdio.h>

int main() {
FILE *file;
char buffer[100];

// Open the file for reading


file = fopen("example.txt", "r");

// Check if the file was successfully opened


if (file == NULL) {
perror("Error opening file");
return 1;
}

// Read data from the file


if (fgets(buffer, sizeof(buffer), file) != NULL) {
printf("Read from file: %s", buffer);
}

// Close the file


fclose(file);

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.

Example: Handling Errors


c
Copy code
if (file == NULL) {
perror("Error opening file");
return 1;
}

5. Close the File

After performing file operations, close the file using fclose to free up resources and ensure that
any buffered data is written to the file.

Example: Closing 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>

// defining main with arguments


int main(int argc, char* argv[])
{
printf("You have entered %d arguments:\n", argc);

for (int i = 0; i < argc; i++) {


printf("%s\n", argv[i]);
}
return 0;
}
Output
You have entered 4 arguments:
./main
geeks
for
geeks
Properties of Command Line Arguments in C
1. They are passed to the main() function.
2. They are parameters/arguments supplied to the program when it is invoked.
3. They are used to control programs from outside instead of hard coding those values inside the code.
4. argv[argc] is a NULL pointer.
5. argv[0] holds the name of the program.
6. argv[1] points to the first command line argument and argv[argc-1] points to the last argument.

You might also like