[go: up one dir, main page]

0% found this document useful (0 votes)
13 views11 pages

Unit-4 Imp

The document provides a comprehensive overview of pointers in C, including their definition, declaration, initialization, and arithmetic operations. It also covers dynamic memory allocation functions such as malloc, calloc, realloc, and free, along with examples. Additionally, it discusses command line arguments, structures, and arrays of structures with relevant syntax and example programs.

Uploaded by

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

Unit-4 Imp

The document provides a comprehensive overview of pointers in C, including their definition, declaration, initialization, and arithmetic operations. It also covers dynamic memory allocation functions such as malloc, calloc, realloc, and free, along with examples. Additionally, it discusses command line arguments, structures, and arrays of structures with relevant syntax and example programs.

Uploaded by

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

Q) Define pointer and explain about pointer declaration and initialization?

Pointers
 A pointer in C is a variable that stores the memory address of another variable.
 Pointers allow you to indirectly access and manipulate the values stored in the memory
locations they point to.
 Pointers are commonly used in C for dynamic memory allocation, array and structure
operations, and passing variables by reference to functions.

Pointer declaration
Pointer declaration defines a pointer variable. It specifies the data type and name of the pointer.

Syntax: data_type *pointer_name;


Where:
 data_type is the type of data the pointer will point to (e.g., int, char, float).
 * is the asterisk symbol, which indicates that the variable is a pointer.
 pointer_name is the name given to the pointer variable.

Example: int *ptr;


This declares a pointer named ptr that points to an integer value.

Pointer initialization
Pointer initialization is the process of assigning a memory address to a pointer variable.

Syntax: type *pointer_name = &variable_name;


Example:
int a = 10;
int *ptr = &a;
In this example:
 ‘a’ is a variable with the value 10.
 &a gets the memory address of ‘a’.
 ptr is a pointer variable that is initialized with the memory address of ‘a’.

Example program:
#include <stdio.h>
void main()
{
int a = 10;
int *ptr;
ptr = &a;
printf("Value of a: %d\n", a);
printf("Memory address of a: %p\n", &a);
printf("Value of ptr (memory address): %p\n", ptr);
printf("Value at ptr (value of a): %d\n", *ptr);
}
Q) Briefly describe about pointer arithmetic in C?
Pointer arithmetic
 Pointer arithmetic allows user to manipulate memory addresses by performing arithmetic
operations on pointers.
 The value of the pointer changes based on the size of the data type it points to.
Importance of pointer arithmetic
 Pointer arithmetic improves memory access speed.
 It helps manage dynamic memory allocation.
 It's necessary for low-level system programming.

Impossible operations in pointer arithmetic


Adding Two Pointers
 User can’t add two pointers together. It doesn’t make sense to add memory addresses.
 Example (Invalid):
int *p1, *p2;
p1 + p2; // NOT ALLOWED
Multiplying or Dividing Pointers
 User can’t multiply or divide pointers.
 Example (Invalid):
int *p;
p * 2; // NOT ALLOWED
Subtracting Pointers from Different Arrays
 Subtracting pointers is only allowed if both pointers belong to the same array.
 Example (Invalid):
int arr1[5], arr2[5];
int *p1 = arr1, *p2 = arr2;
int diff = p1 - p2; // NOT ALLOWED (different arrays)

Possible operations in pointer arithmetic


Add a Number to a Pointer
 User can add an integer to a pointer to move it forward by that many elements.
 Example:
int arr[5] = {10, 20, 30, 40, 50};
int *p = arr;
p = p + 2; // Points to arr[2] (value 30)
Subtract a Number from a Pointer
 User can subtract an integer from a pointer to move it backward by that many elements.
 Example:
int arr[5] = {10, 20, 30, 40, 50};
int *p = &arr[3]; // Points to arr[3] (value 40)
p = p - 2; // Points to arr[1] (value 20)
Subtract Two Pointers
 If two pointers point to elements in the same array, you can subtract them to find the
number of elements between them.
 Example:
int arr[5] = {10, 20, 30, 40, 50};
int *p1 = &arr[4]; // Points to arr[4]
int *p2 = &arr[1]; // Points to arr[1]
int diff = p1 - p2; // diff = 3 (4 - 1)
Increment a Pointer
 User can use ++ to move a pointer to the next element.
 Example:
int arr[5] = {10, 20, 30, 40, 50};
int *p = arr;
p++; // Moves to arr[1] (value 20)

Decrement a Pointer
 User can use -- to move a pointer to the previous element.
 Example:
int arr[5] = {10, 20, 30, 40, 50};
int *p = &arr[2]; // Points to arr[2] (value 30)
p--; // Moves to arr[1] (value 20)
Compare Pointers
 User can compare pointers using comparison operators (==, !=, <, >, <=, >=) if they point
to elements of the same array.
 Example:
int arr[5] = {10, 20, 30, 40, 50};
int *p1 = &arr[1];
int *p2 = &arr[3];
if (p1 < p2)
{
printf("p1 points to an earlier element.\n");
}

Program:
#include <stdio.h>
int main()
{
int arr[5] = {1, 2, 3, 4, 5};

int* ptr1 = arr;


int* ptr2 = arr + 2; // ptr2 points to the third element

// Possible operations
printf("Possible operations:\n");
printf("ptr1 + 1 = %p\n", ptr1 + 1);
printf("ptr1 - 1 = %p\n", ptr1 - 1);
printf("ptr2 - ptr1 = %d\n", ptr2 - ptr1); // Output: 2
printf("ptr1 < ptr2 = %d\n", ptr1 < ptr2); // Output: 1 (true)
return 0;
}
Q) Explain about dynamic memory allocation functions with example
programs.

Dynamic Memory Allocation


• Dynamic Memory Allocation memory is allocated at runtime, once the memory is
allocated, the memory size can be changed.
• The C language supports 4 types of dynamic memory allocation functions, which are
a) malloc( )
b) calloc( )
c) realloc( )
d) free( )
a) malloc( ) function
• It is used to allocate a single block of memory dynamically at run time of a program.
• If memory is allocated successfully, then it returns first byte address (starting address of
the block) otherwise it returns NULL pointer.
• It allocates memory and returns “void data type pointer”. So, type casting is needed.
• Syntax: pointer_variable = (datatype *) malloc (n*sizeof(datatype));
• Example: ptr=(int *)malloc(n*sizeof(int));

Example program

//Program to find the sum of elements of array using malloc() function.


#include <stdio.h>
#include <stdlib.h>
void main()
{
int n,*ptr,i,sum;
printf("Enter no.of elements: ");
scanf("%d", &n);
ptr=(int *)malloc(n*sizeof(int));
if(ptr==NULL)
{
printf("Memory allocation failed. Exit..");
exit(0);
}
printf("Enter elements of the array:");
for(i=0;i<n;i++)
{
scanf("%d",(ptr+i));
sum=sum+*(ptr+i);
}
printf("The sum of all array elements is: %d\n",sum);
free(ptr);
}
b) calloc( ) function
• It is used to allocate multiple blocks of memory dynamically at run time of a program.
• If memory is allocated successfully, then it returns first byte address (starting address of
the block) otherwise it returns NULL pointer.
• It allocates memory and returns “void data type pointer”. So, type casting is needed.
• Syntax: pointer_variable = (datatype *) calloc (n, n*sizeof(datatype));
• Example: ptr=(int *)calloc(n, n*sizeof(int));

Example program

//Program to reverse array elements using calloc() function.


#include <stdio.h>
#include <stdlib.h>
void main()
{
int n,*ptr,i;
printf("Enter no.of elements: ");
scanf("%d", &n);
ptr=(int *)calloc(n,n*sizeof(int));
if(ptr==NULL)
{
printf("Memory allocation failed. Exit..");
exit(0);
}
printf("Enter elements of the array:");
for(i=0;i<n;i++)
{
scanf("%d",(ptr+i));
}
printf("Reverse array is: ");
for(i=n-1;i>=0;i--)
{
printf("%d ",*(ptr+i));
}
free(ptr);
}

c) realloc() function:
• It is used to resize dynamically allocated memory blocks.
• It creates mew memory and transfers old data into newly created memory space.
• If realloc() is not successful to create memory, then user loses previous data.
• Syntax: pointer_variable = (datatype *) realloc (old_pointer, new_memory_size);
• Example: new_ptr=(char *)realloc(old_ptr, 20);
Example program

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void main()
{
char *p,*q;
p=(char *)malloc(10); // old memory size
printf("Enter your name: ");
scanf("%s",p);
printf("%s \n",p);
q=(char *)realloc(p,20); // new memory size
printf("Enter new string: ");
scanf("%s",q);
printf("%s",q);
}

d) free() function:
 This function is used to deallocate memory which is allocated dynamically. This function
takes only one parameter that is also a pointer.
 Syntax: free(pointer_variable);

Example program

#include <stdio.h>
#include <stdlib.h>
void main()
{
int *ptr=(int *)malloc(sizeof(int));
*ptr = 15;
free(ptr);
printf("%d", *ptr);
}
Q) Discuss briefly about command line arguments in C.

Command line arguments


 Command line arguments are the parameters passing to main() function from the
command line.
 Command line argument is a parameter supplied to the program when it is invoked.
 Command line argument is an important concept in C programming. It is mostly used
when user need to control the program from outside.

Syntax: int main(int argc, char** argv[ ])

When command line arguments are passed main() method receives them with the help of two
formal parameters and they are,

 int argc
 char** argv[ ]

int argc - It is an integer argument used to store the count of command line arguments are passed
from the command line.

char** argv[ ] - It is a character pointer array used to store the actual values of command line
arguments are passed from the command line.

User must make sure that in command line argument, argv[0] stores the name of the program or
name of the file, similarly argv[1] gets the pointer to the first command line argument that has
been supplied by the user, and *argv[n] denotes the last argument of the list.

Example Program:

// Program on command line arguments. #include<stdio.h>


int main(int argc, char** argv)
{
int i;
printf("The number of arguments are: %d\n",argc);
printf("The arguments are: \n");
for(i=0;i<argc;i++)
{
printf("arg[%d]: %s\n",i,argv[i]);
}
return 0;
}
Q) Define structure and explain about structure declaration and initialization?

Structure
 A structure is a collection of elements of different data types.
 A structure is also called a user-defined data type.
 All elements of a structure are stored at contiguous memory locations.
 A variable of structure type can store multiple data items of different data types under a
single name.
 For example, the data of an employee in a company, such as name, employee ID, salary,
address, and phone number, can be stored in a structure data type.

Syntax:
struct <tag_name>
{
data_type1 var1,var2,var3,...;
data_type2 var1,var2,var3,...;
……..
data_typeN var1,var2,var3,....;
};

Example:
struct student
{
char name[10];
int rollno;
float marks;
};
 A structure can be defined using the keyword "struct".
 The tag-name specifies the name of the structure.
 Defining a structure without a structure variable is known as a structure template, but its
size is not always 1 byte. The size of a structure template depends on the sizes of its
members.

Structure Variable Declaration


Structure variable declaration is the process of declaring variables of a structure type that has
already been declared. It reserves memory space for the variables and allows them to be used in the
program.

Syntax:
struct <tag_name>
{
datatype1 var1,var2,..;
datatype2 var1,var2,..;
..........
datatypeN var1,var2,..;
};
struct <tag_name> structure_variable_name;
Example:
struct student
{
char name[10];
int rollno;
float marks;
};
struct student s1;

Structure Variable Initialization


Structure Variable Initialization is the process of assigning initial values to the members of a
structure variable.

Syntax:
struct <tag_name>
{
datatype1 var1,var2,..;
datatype2 var1,var2,..;
..........
datatype3 var1,var2,..;
};
struct <tag_name> structure_variable_name={val1,valu2,...};

Example:
struct student
{
char name[10];
int rollno;
float marks;
};
struct student s1={“Ananth”,123,97.45};

Example Program
// Simple example program on structures.
#include <stdio.h>
struct student
{
char name[30];
int rollno;
float marks;
};
void main()
{
struct student s1={"Ananth",123,97.75};
printf("Name: %s\n", s1.name);
printf("Roll no: %d\n", s1.rollno);
printf("Marks: %f\n", s1.marks);
}
Q) Explain about array of structures with example program in C?
Array of structures
 An array of structures is a collection where each item (structure variable) is a structure, used
to store related information together.
 Structures group different types of data under one name, making it easy to organize.
 All items (structure variables) in the array follow the same structure, keeping the data
consistent.
 You can access each structure in the array using an index, like with any array.
 The fields (parts) of a structure can be accessed using the dot (.) operator.
 Arrays of structures help organize and manage multiple sets of related information.
 They are often used for things like student records, employee details, or product lists.

Syntax:
struct StructureName
{
data_type field1;
data_type field2;
};
struct StructureName arrayName[arraySize]; // Declare an array of the structure

// Accessing fields in the array


arrayName[index].field1;
arrayName[index].field2;
Example:
struct student
{
char name[50];
int rollno;
float marks;
};
struct student s[5];

Example Program:
// Program to implement array of structures.
#include<stdio.h>
void main()
{
struct Student
{
char name[10];
int rollno;
float marks;
};
int n,i;
printf("How many students details you want: ");
scanf("%d",&n);
struct Student s[n]; // Arry of structures
for(i=0;i<n;i++)
{
printf("Enter student-%d details: ",i+1);
scanf("%s%d%f",s[i].name,&s[i].rollno,&s[i].marks);
}
printf("All students details are: \n");

for(i=0;i<n;i++)
{
printf("Name:%s ",s[i].name);
printf("Roll Number:%d ",s[i].rollno);
printf("Marks:%.2f \n",s[i].marks);
}
}

Q) Write the differences between structures and unions?

Difference between structure and union


Structure Union
It uses ‘struct’ keyword to define it. It uses ‘union’ keyword to define it.
Each member has its own memory space. All members share the same memory space.

The size of a structure is the sum of sizes of The size of a union is the size of its largest
its members. member.

All members store their values at a time. Only one member can store value at a time.

All members can be accessed at the same Only the last assigned member can be
time. accessed.

Suitable for grouping related data of different Suitable for saving memory when only one
types. member is needed at a time.

It takes more memory as compared to union. It takes less memory as compared to structure.
struct student union student
{ {
char grade; char grade;
float marks; float marks;
}; };
Here, size of structure is 5 bytes. Here, size of union is 4 bytes.

You might also like