0% found this document useful (0 votes)
8 views97 pages

C Programming: Structures and Pointers

The document provides an overview of key programming concepts including structures, pointers, and dynamic memory allocation in C and C++. It explains memory allocation for structures, the use of pointers and double pointers, and the differences between malloc and calloc for dynamic memory allocation. Additionally, it covers how to handle arrays and strings using pointers, as well as the syntax for dynamic memory allocation using the new operator.

Uploaded by

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

C Programming: Structures and Pointers

The document provides an overview of key programming concepts including structures, pointers, and dynamic memory allocation in C and C++. It explains memory allocation for structures, the use of pointers and double pointers, and the differences between malloc and calloc for dynamic memory allocation. Additionally, it covers how to handle arrays and strings using pointers, as well as the syntax for dynamic memory allocation using the new operator.

Uploaded by

arpanmahanty01
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Lecture-1

Overview
Overview
Of Some
Selected Topics
 Structures
 Union
 Pointers
 Bit Specified variable
 DMA
(Dynamic Memory Allocation)
Structures
Memory Allocation to Structures

Unless we associate a variable


with defined structure
no memory space is allocated
Name of ith student

Enrollment no. of ith student

Marks of ith student

Class S.N. of ith student


Further
expanding
Student Record
One Department Elective

One Institute Elective

Three Core Courses


Compulsory for all students
The Data Type is either
int
unsigned int
Or signed int

Bit length is number of bits used


For signed int at least two bits
to be used , one for sign
Illustration for BFS

Struct Example
{
int a;
unsigned sex_code :1 ;
int b;
int d:3;
signed int c:2 ;
float marks;
int e:2 ;
float value;
};
0 15
a
0 15 a

0 15
Sex_code
0 15 a

0 15
Sex_code

0 15 b
0 15 a

0 15
Sex_code

0 15 b

0 1 2 15 d
0 15 a

0 15
Sex_code

0 15 b

0 1 2 3 4 15 d,c
0 15 a

0 15
Sex_code

0 15 b

0 1 2 3 4 15 d,c

0 3
1 marks
0 15 a

0 15
Sex_code

0 15 b

0 1 2 3 4 15 d,c

0 3
1 marks

0 1
e
0 15 a

0 15
Sex_code

0 15 b

0 1 2 3 4 15 d,c

0 3
1
marks
0 1 15 e

0 3
1value

18 bytes
Efficient way of
defining structure for this case
Struct Example
{
unsigned sex_code :
1;
int d: 3;
int c: 2 ;
int e: 2 ;
int a;
int b;
float marks;
float value;
};
Sex_code, d ,c , e ( 1—3—2—2)
0 1 2 3 4 5 6 7

marks

value

14 bytes
Pointers
Point to Ponder
int value1, *p1;
float value2, *p2 ;
p1 = &value1;
p2 = &value2;

Why data type is


to be associated with pointer ?
When it holds integer address!
#include <stdio.h>
int main()
{
int *ptrq, q;
q = 50;

/* address of q is assigned to ptr */

ptrq = &q;

/* display q's value using ptr variable */


printf("%d", *ptrq);
return 0;
Pointer to Pointer/ double pointer
int num=123;
int *pr2;
int **pr1;
pr1 = &pr2;
pr2 = &num
Use of double pointer
/* Possible ways to find value of variable
num*/

printf("\n Value of num is: %d", num);

printf("\n Value of num using pr2 is: %d", *pr2);

printf("\n Value of num using pr1 is: %d", **pr1);

int b = *pr2;
c = b+(*pr2)
int b = *pr2;
c = b+(*pr2)
0r c = b+ **pr1

Or C = 2*(**pr1)
All will lead c= 246 but num does not change

num = 2*(**pr1) or **pr1 = 2*(*pr2)


Both will lead value of num As 246
/*Possible ways to find address of num*/

printf("\n Address of num is: %p", &num);

printf("\n Address of num using pr2 is: %p", pr2);

printf("\n Address of num using pr1 is: %p", *pr1);


Double Pointer in C
int main()
{
int var = 789;

// pointer for var


int* ptr2;

// double pointer for


ptr2
int** ptr1;
// storing address of var in ptr2
ptr2 = &var;
// Storing address of ptr2 in ptr1
ptr1 = &ptr2;
// Displaying value of var using
// both single and double pointers
printf("Value of var = %d\n", var);
printf("Value of var using single
pointer
= %d\n", *ptr2);
Double Pointer in C++
int val = 169;

// storing address of val to pointer ptr.


int *ptr = &val;

int **double_ptr = &ptr;

// pointer to a pointer declared which is


pointing to an integer.
What will be the size of a
pointer to a pointer in C
double pointer behave similarly
to a normal pointer both in C &
C++

So, the size of the variable of the


double-pointer and the size of the
normal pointer variable is always
equal.
Pointer Increment
& Scale factor
Pointers & Arrays
One Dimensional Array
Static int x(5) = { 1, 2, 3, 4, 6}

Int *p

variable X[0] X[1] X[2] X[3] X[4]

value 1 2 3 4 6
address 1000 1002 1004 1006 1008
x is base address
x and &x[0] is same and is 1000
p = x is same as p = &x[0]
x is a pointer constant
p is a pointer variable

p &x[0] *p …….. x[0]


p+1 &x[1] *(p+1) … x[1]
p+2 &x[2] *(p+2) … x[2]
p+3 &x[3] .
p+4 &x[4] .
variable X[0] X[1] X[2] X[3] X[4]
value 1 2 3 4 6
address 1000 1002 1004 1006 1008
Address of x[i] =
Base address of array X +
i* scale factor for int.
=X+2*i
Scale factor is 2 for integer, 4 for float & 1 for char

ith element = *(X + 2 * i)


Two Dimensional Array
static int a[2][3];
int *p ;
p=a ; //*or p = &a[0][0]

p ….. Pointer to first Row

(a+i) or a[i] …. Pointer to ith Row

*(a+i) …. pointer to the first element in the ith Row


*(a+i) + j …… Pointer to jth element in ith Row
*(*(a+i) + j) ……. Value of (i,j)th element
( jth element in ith Row)
….. a[0][0] ROW-0
….. a[0][1]
….. a[0][2]
ROW- a[1] …..
1 [0]
a[1] …..
[1]
a[1] …..
[2]

(p+3)+j ………. Address of jth element in


second row
*((p+Max_COL*i)+j) … (i,j)th element
Char NAME [4][16]
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

R O O R K E E \0
U N A \0
M E E R U T \0
D H A R A M S H A L A \0

SPACE ALLOCATED ….. 64 bytes


SPACE USED …… 31 bytes
Static char *name[4] = { “ROORKEE’
“UNA”
“MEERUT”
“DHARAMSHALA”
};
R O O R K E E \0
U N A \0
M E E R U T \0
D H A R A M S H A L A \0

SPACE ALLOCATED ….. 31 bytes


SPACE USED …… 31 bytes
SPACE IS ALLOCATED EXACTLY
WHAT IS REQUIRED

NAME[0] …. Pointer to first String

Name[i] …. Pointer to ith String


POINTERS & CHARACTER STRING
main()
{
char *name;
Int length ;
Char *cptr = name;
Name = “ROORKEE” ;
When(*cptr != ‘\0’)
{
Cptr++ ;
}
Length = cptr – name;
Printf( “\n length of string = %d”, length);
} /*main ends here

USING POINTERS WE CAN HANDLE TABLE OF STRINGS

Char name[20]
Name = “Roorekee”
Static char *name[4] = { “ROORKEE’
“UNA”
“MEERUT”
“DHARAMSHALA”
};
USING ARROW OPERATOR
Index/ Record of
0 Student[0]
1 .
2 .
3 .
. .
. .
48 .
49 Student[49]
DYNAMIC
MEMORY
ALLOCATION
(DMA)
Difference Between

malloc( ) & calloc( )


Important Points !
Important Points !
Ptr May Change or may not Change
Case-1 newsize is Smaller
Case-2 newsize is Larger
Case-1 New size is smaller
Case-2 newsize is Larger

(a)
Case-2 newsize is Larger
(b)
In C++, memory is divided into two parts –

Stack - All the variables that are


declared inside any function take memory
from the stack.

Heap - It is unused memory in the


program that is generally used for
dynamic memory allocation
Dynamic memory allocation
using the new operator

To allocate the space dynamically, the operator


new is used.
It means creating a request for memory
allocation on the free store. If memory is
available, memory is initialized, and the address
of that space is returned to a pointer variable.
Syntax
Pointer_variable = new data_type;

The pointer_varible is of pointer


data_type.

The data type can be int, float,


string, char, etc.
int *m = NULL // Initially we have a NULL
pointer
m = new int // memory is requested to the
Initialize memory

We can also initialize memory using new


operator.

int *m = new int(20);


Float *d = new float(21.01);
Allocate a block of memory

We can also use a new operator to allocate


a block(array) of a particular data type.

For example
int *arr = new int[10]

Here we have dynamically allocated memory for ten


integers which also returns a pointer to the first element
of the array. Hence, arr[0] is the first element and so on.

Common questions

Powered by AI

In C, pointer arithmetic can determine the length of a null-terminated string by advancing a pointer until it reaches the null character '\0'. For example, given 'char name[] = "ROORKEE";', the length can be computed by initializing 'char *ptr = name;' and iterating 'ptr++' while '*ptr != '\0''. The length is then 'ptr - name', effectively counting the characters traversed. This pointer-based approach is efficient for string operations since it avoids direct indexing, leveraging the pointer's ability to navigate contiguous memory blocks .

A double pointer in C, denoted as '**ptr', is a pointer to another pointer. It provides an additional layer of indirection, allowing manipulation and access to both the pointer and the data it points to. For instance, consider 'int var = 789;', 'int* ptr2 = &var;', and 'int** ptr1 = &ptr2;'. Here, 'ptr2' stores the address of 'var', and 'ptr1' stores the address of 'ptr2'. Access to 'var' can be achieved via '*ptr2' or '**ptr1', and the address of 'var' via 'ptr2' or '*ptr1' .

In C, the use of bit fields in structures allows specific control over how many bits are used for each part of a structure, which can significantly reduce memory usage compared to using regular integer fields. For example, struct fields like 'unsigned sex_code : 1' and 'signed int c:2' limit the storage of those fields to just 1 and 2 bits, respectively, instead of 32 bits. An initial example of a struct that uses 18 bytes can be optimized by ordering fields with the smallest bit field widths first, achieving a more compact arrangement that uses 14 bytes instead .

In C, the scale factor in pointer arithmetic is determined by the data type's size. For an integer array, the scale factor is 2 bytes, meaning pointer arithmetic accounts for this when iterating through elements. For example, if 'int x[5] = {1, 2, 3, 4, 6};' and 'int *p = x;', then 'p+1' will refer to 'x[1]', located 2 bytes away from 'x[0]'. Similarly, for float, the scale factor is 4 bytes, and for char, it is 1 byte. This scale factor ensures that pointer operations address subsequent elements accurately by considering the data type's byte size .

Using a static char array for strings, such as 'char NAME[4][16]', preallocates a fixed memory space of 64 bytes to store strings, facilitating efficient direct access but potentially wasting space if the strings are shorter than allocated space. In contrast, dynamic string handling with pointers, such as 'static char *name[4] = {"ROORKEE", "UNA", "MEERUT", "DHARAMSHALA"};', allocates only the required space for each string tailered to actual sizes, totaling 31 bytes. The dynamic method, though potentially more complex due to the pointer manipulation, maximizes memory conservation by allocating exactly the necessary amount of space for the string contents .

Memory for a structure instance in C is allocated only when a variable of the defined structure type is declared. The structure definition itself does not allocate memory. For example, declaring 'struct Example { int a; float b; };' outlines the structure, but memory is only allocated with a declaration like 'struct Example inst;', where 'inst' reserves space for 'int a' and 'float b'. This allocation occurs based on the combined sizes of the members, taking into consideration padding and alignment, but it won't be utilized until an instance is created .

In C++, dynamically allocating an array of primitive types with the new operator involves requesting memory for raw storage. For example, 'int *arr = new int[10];' allocates space for ten integers. However, for objects, allocation also involves invoking the constructor for each element. For example, 'MyClass *objArr = new MyClass[10];' calls MyClass's default constructor for each element. The primary distinction is that objects require construction, thus potentially initializing internal object data, whereas primitive types receive a block of raw memory with no implicit initialization .

Dynamic memory allocation with the new operator in C++ allows memory to be allocated from the heap rather than the stack. This is useful for managing data whose size or lifespan cannot be determined at compile time. The stack is used for fixed-size allocations that should automatically deallocate, while the heap caters to dynamic allocations that need manual deallocation. For example, to allocate a block of memory for ten integers and initialize one, you could use: 'int *arr = new int[10]; arr[0] = 42;'. This code allocates memory on the heap, and it's vital to release it later using 'delete[] arr;' to prevent memory leaks .

The primary differences between malloc() and calloc() in C lie in their initialization of allocated memory and their parameters. malloc() allocates a block of memory but leaves the memory uninitialized, which means the contents could be any arbitrary value. It takes a single parameter specifying the number of bytes to allocate. calloc(), on the other hand, allocates memory and initializes all bits to zero, ensuring the memory is blanked out. It takes two parameters: the number of elements and the size of each element, enhancing safety for zero-initialized memory needs. calloc() is preferred when zero initialization is required to prevent potential errors from garbage values .

Associating a data type with a pointer in C is crucial because it informs the compiler about the type of data that the pointer will point to, affecting pointer arithmetic and dereferencing. The data type determines the step size for pointer increments or decrements, and how many bytes should be accessed at a location when dereferenced. For example, if a pointer is associated with an 'int', increments traverse by 4 bytes (on typical systems), and dereferencing retrieves a 4-byte integer. Without specifying a type, these crucial operations cannot be correctly or safely performed .

You might also like