0% found this document useful (0 votes)
5 views

C lecture 5.2

The document explains various concepts related to arrays and pointers in C programming, including passing arrays to functions, using pointers to access array elements, and dynamic memory allocation with functions like malloc() and calloc(). It also discusses potential drawbacks of using pointers, such as memory leaks and debugging challenges. Examples are provided to illustrate each concept, including the use of pointer-to-pointer and arrays of pointers.

Uploaded by

devlina.karmakar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

C lecture 5.2

The document explains various concepts related to arrays and pointers in C programming, including passing arrays to functions, using pointers to access array elements, and dynamic memory allocation with functions like malloc() and calloc(). It also discusses potential drawbacks of using pointers, such as memory leaks and debugging challenges. Examples are provided to illustrate each concept, including the use of pointer-to-pointer and arrays of pointers.

Uploaded by

devlina.karmakar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Passing an array to a function:

In C programming, you can pass en entire array to functions.


calculate the sum of array elements by passing to a function:
#include <stdio.h>
float calculateSum(float age[]);
int main()
{
float result, age[] = {23.4, 55, 22.6, 3, 40.5, 18};
result = calculateSum(age);
printf("Result = %.2f", result);
return 0;
}
float calculateSum(float age[])
{
float sum = 0.0;
for (int i = 0; i < 6; ++i)
{
sum += age[i];
}
return sum;
}
Passing two-dimensional arrays:
#include <stdio.h>
void displayNumbers(int num[2][2]);
int main()
{
int num[2][2];
printf("Enter 4 numbers:\n");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
scanf("%d", &num[i][j]);
displayNumbers(num);
return 0;
}
void displayNumbers(int num[2][2])
{
printf("Displaying:\n");
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 2; ++j)
{
printf("%d\n", num[i][j]);
}
}
}
Pointer to an array:
An array name is a constant pointer to the first element of the array. Therefore, in the declaration
double balance[50];

balance is a pointer to &balance[0], which is the address of the first element of the array balance. Thus, the following
program fragment assigns p as the address of the first element of balance

double *p;
double balance[10];
p = balance;

It is legal to use array names as constant pointers, and vice versa. Therefore, *(balance + 4) is a legitimate way of
accessing the data at balance[4].
#include <stdio.h>
int main ()
{
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
double *p;
int i;
p = balance;
printf( "Array values using pointer\n");
for ( i = 0; i < 5; i++ )
{
printf("*(p + %d) : %f\n", i, *(p + i) );
}
printf( "Array values using balance as address\n");
for ( i = 0; i < 5; i++ )
{
printf("*(balance + %d) : %f\n", i, *(balance + i) );
}
return 0;
}
Array of Pointers:
There may be a situation when we want to maintain an array, which can store pointers to an int or char or any other data type available. Following is the declaration of an array
of pointers to an integer −
int *ptr[MAX];
It declares ptr as an array of MAX integer pointers. Thus, each element in ptr, holds a pointer to an int value.
#include <stdio.h>
const int MAX = 3;
int main ()
{
int var[] = {10, 100, 200};
int i, *ptr[MAX];
for ( i = 0; i < MAX; i++)
{
ptr[i] = &var[i];
}
for ( i = 0; i < MAX; i++)
{
printf("Value of var[%d] = %d\n", i, *ptr[i] );
}
return 0;
}
Pointer to String:

#include <stdio.h>
int main()
{
char *cities[] = {"India", "Indonesia"};
int i;
for(i = 0; i < 2; i++)
printf("%s\n", cities[i]);
return 0;
}
In the above pointer to string program, we declared a pointer array of character data types and then few strings like
"India", "Indonesia" where initialized to the pointer array (*cities[]).
#include <stdio.h>
#include <string.h>
void function(char**);
int main()
{
char *str = "Pointer-to-string";
int i, j = strlen(str);
for(i = 0; i < j; i++)
printf("%c", *str++);
return 0;
}

*str is a char pointer variable which is initialized by a string "Pointer-to-String". Then strlen() is used to find the length of the
string to do iteration using for loop is done to print the complete characters store with the variable name *str.
Pointer to pointer:
A pointer holds the address of another variable of same type. When a pointer holds the address of another pointer then such
type of pointer is known as pointer-to-pointer or double pointer.
Declaration:
int **pr;
Here pr is a double pointer. There must be two *’s in the declaration of double pointer.
As per the diagram, pr2 is a normal pointer that holds the address of an integer variable num. There is another pointer
pr1 in the diagram that holds the address of another pointer pr2, the pointer pr1 here is a pointer-to-pointer (or double
pointer).

Values from above diagram:


Variable num has address: XX771230
Address of Pointer pr1 is: XX661111
Address of Pointer pr2 is: 66X123X1
#include <stdio.h>
int main()
{
int var;
int *ptr;
int **pptr;
var = 3000;
ptr = &var;
pptr = &ptr;
printf("Value of var = %d\n", var );
printf("Value available at *ptr = %d\n", *ptr );
printf("Value available at **pptr = %d\n", **pptr);
return 0;
}
Memory usage:
On 64-bit machines, pointers take up 8 bytes of memory (on 32-bit machines, they take up 4 bytes).
Dynamic memory allocation:
Dynamic Memory Allocation is manual allocation and freeing of memory according to your programming needs.
Dynamic memory is managed and served with pointers that point to the newly allocated memory space in an area which
we call the heap.
The <stdlib.h> library has functions responsible for Dynamic Memory Management.

malloc(): Allocates the memory of requested size and returns the pointer to the first byte of allocated space.
calloc(): Allocates the space for elements of an array. Initializes the elements to zero and returns a pointer to the memory.
realloc(): It is used to modify the size of previously allocated memory space.
Free(): Frees or empties the previously allocated memory space.
C malloc() Function:
The C malloc() function stands for memory allocation. It is a function which is used to allocate a block of memory
dynamically. It reserves memory space of specified size and returns the null pointer pointing to the memory location.
The pointer returned is usually of type void. It means that we can assign C malloc() function to any pointer.

Syntax of malloc() Function:


ptr = (cast_type *) malloc (byte_size);
ptr is a pointer of cast_type.
The C malloc() function returns a pointer to the allocated memory of byte_size.

Example:
ptr = (int *) malloc (50)
When this statement is successfully executed, a memory space of 50 bytes is reserved. The address of the first byte of
reserved space is assigned to the pointer ptr of type int.
#include<stdio.h>

#include <stdlib.h>

int main()

int* ptr1;

ptr1 = (int*) malloc (3 * sizeof(int));

if(ptr1==NULL)

printf("Memory not allocated. \n");

else

printf("Memory allocated succesfully. \n");

printf("The address of the pointer is:%u\n ", ptr1);

for(int i=0;i<3;i++)

ptr1[i] = i;

for(int i=0;i<3;i++)

printf("%d\n", ptr1[i]);

return 0;

}
C calloc() function:
C provides another function to dynamically allocate memory which sometimes better than the malloc() function. Its
syntax is:
void *calloc(size_t n, size_t size);
int *p;
p = (int*)calloc(5, 4);
This allocates 20 bytes of contiguous memory space from the heap and assigns the address of first allocated byte to
pointer variable p.
To make our program portable and more readable sizeof() operator is used in conjunction with calloc().
int *p;
p = (int*)calloc(5, sizeof(int));
The difference between calloc() and malloc() function is that memory allocated by malloc() contains garbage value
while memory allocated by calloc() is always initialized to 0.
#include<stdio.h>

#include<stdlib.h>

int main()

int *p, i, n;

printf("Enter the size of the array: ");

scanf("%d", &n);

p = (int*)calloc(n, sizeof(int));

if(p==NULL)

printf("Memory allocation failed");

exit(1);

for(i = 0; i < n; i++)

printf("Enter %d element: ", i);

scanf("%d", p+i);

printf("\nprinting array of %d integers\n\n", n);

for(i = 0; i < n; i++)

printf("%d ", *(p+i));

return 0;

}
Drawbacks of pointer:

• Uninitialized pointers might cause segmentation fault.


• Dynamically allocated block needs to be freed explicitly. Otherwise, it would lead to memory leak.
• Pointers are slower than normal variables.
• If pointers are updated with incorrect values, it might lead to memory corruption.
• Basically, pointer bugs are difficult to debug. Its programmers responsibility to use pointers effectively and
correctly.

You might also like