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

LabManual 07

This lab manual provides an introduction to C pointers, covering their declaration, initialization, and usage in arrays and functions. It includes theoretical explanations, practical examples, and exercises to enhance understanding of pointers, void pointers, null pointers, and dynamic memory allocation. The manual aims to equip students with the necessary skills to manage memory effectively in C programming.

Uploaded by

c.sunjid707
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)
4 views

LabManual 07

This lab manual provides an introduction to C pointers, covering their declaration, initialization, and usage in arrays and functions. It includes theoretical explanations, practical examples, and exercises to enhance understanding of pointers, void pointers, null pointers, and dynamic memory allocation. The manual aims to equip students with the necessary skills to manage memory effectively in C programming.

Uploaded by

c.sunjid707
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/ 9

AMERICAN INTERNATIONAL UNIVERSITY-BANGLADESH (AIUB)

FACULTY OF SCIENCE & INFORMATION TECHNOLOGY


DEPARTMENT OF COMPUTER SCIENCE

LAB MANUAL 07
CSC1102
Programming Language 1
[EEE]

Prepared By:
M. ARIFUR RAHMAN
1
TITLE

A Brief Introduction to C Pointers

PREREQUISITE

• To know about C variables


• To be able to use printf() and scanf()
• To know about C arrays
• To know about C functions
• To know about loop control structure
• To know about decision control structure

OBJECTIVE

• To get a basic idea about C pointers


• To gain experience with pointer declaration, initialization and access
• To understand about pointer in array and function
• To know about void pointer and null pointer
• To be able to do memory management using pointer
• To be able to solve the exercises and lab work at the end of this manual

THEORY

POINTER

A pointer is a variable that stores the location of memory. In more fundamental terms, a
pointer stores the address of a variable. In more picturesque terms, a pointer points to a
variable. A pointer has to be declared just like any other variable. For example: int *p; is a
pointer to an integer. Adding an asterisk (called the de-referencing operator) in front of a
variable's name declares it to be a pointer to the declared type. For example: int *p, q;
declares p, a pointer to int, and q an int and the instruction: p=&q; stores the address of q in
p. After this instruction, conceptually, p is pointing at q.
The program below will help clarify the concept of pointer variable.
#include<stdio.h>
void main()
{
int x;
x = 10;
int*p;
p = &x;
int y;
2
y = *p;
printf("Address of integer variable x: %d",&x);
printf("\n");
printf("Value stored in the memory area of variable x: %d",x);
printf("\n");
printf("Address of integer pointer variable *p: %d",&p);
printf("\n");
printf("Address stored in the area of pointer variable *p: %d",p);
printf("\n");
printf("Address of integer variable y: %d",&y);
printf("\n");
printf("Value pointed to by the pointer *p: %d",*p);
printf("\n");
printf("Value stored in the memory area of variable y: %d",y);
}

POINTERS AND ARRAYS

An alternative idea of an array is to consider it as simply a block of memory. An array can be


accessed with pointers as well as with [] square brackets. The name of an array variable,
standing alone, is actually a pointer to the first element in the array. So, any operation that
can be achieved by array subscripting can also be done with pointers or vice-versa.
The program below will help clarify the concept of pointers and arrays.

#include<stdio.h>

void main()

float numbers[5] = {22.5,34.8,46.8,59.1,68.3};

printf("1st element of array numbers: %f",numbers[0]);

printf("\n");

printf("1st element of array numbers: %f",*numbers);

printf("\n");

printf("3rd element of array numbers: %f",numbers[2]);

printf("\n");

printf("3rd element of array numbers: %f",*(numbers+2));

printf("\n");

float *p;

p = numbers; //&numbers[0]

3
printf("1st element of array numbers: %f",p[0]);

printf("\n");

printf("1st element of array numbers: %f",*p);

printf("\n");

printf("3rd element of array numbers: %f",p[2]);

printf("\n");

printf("3rd element of array numbers: %f",*(p+2));

printf("\n");

int i;

for(i=0, p=numbers; i<5; i++, p++)

printf("Element %d",(i+1));

printf(" of array numbers: %f",*p);

printf("\n");

POINTER ARITHMETIC

When a pointer value is increased by a number n, it actually increases by n*sizeof (data type)
number of bytes.

The program below will help clarify the concept of pointer arithmetic.

#include <stdio.h>

void main()

int numbers[5] = {22,34,46,59,68};

int *p, i;

p = numbers;

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

(*p)++;

printf("Element %d",(i+1));
4
printf(" of array numbers: %d",*p);

printf("\n");

p++;

printf("Element %d",(p-numbers+1));

printf(" of array numbers: %d ",*(--p));

printf("\n");

printf("Element %d",(p-numbers+1));

printf(" of array numbers: %d ",*(--p));

printf("\n");

printf("Element %d",(p-numbers+1));

printf(" of array numbers: %d ",*(--p));

printf("\n");

printf("Element %d",(p-numbers+1));

printf(" of array numbers: %d ",--(*(--p)));

printf("\n");

printf("Element %d",(p-numbers+1));

printf(" of array numbers: %d",(*(--p))--);

POINTER AND FUNCTION

Passing arguments to functions by value, there is no direct way for the called function to alter
a variable in the calling function. Pointer arguments enable a function to access and change
objects in the function that called it.
The program below will help clarify the concept of pointer and functions.

#include<stdio.h>

void swap(int *a,int *b);

void main()

int num1=5,num2=10;

swap(&num1, &num2);

5
printf("Number1 = %d ",num1);

printf("Number2 = %d ",num2);

void swap(int *a,int *b)

int t;

t=*a;

*a=*b;

*b=t;

VOID POINTERS

The void type of pointer is a special type of pointer which represents the absence of type. So
void pointers are pointers that point to a value that has no type (and thus also an
undetermined length and undetermined dereference properties). This allows void pointers to
point to any data type, int, float, char, double or any type of array. But the data pointed by
them cannot be directly dereferenced, since we have no type to dereference to. So need to
cast the address in the void pointer to some other pointer type that points to a concrete data
type before dereferencing it.

The program below will help clarify the concept of void pointers.

#include<stdio.h>

void increase (void*data, int psize)

if ( psize == sizeof(char) )

char*pchar;

pchar=(char*)data;

++(*pchar);
}
else if (psize == sizeof(int) )

int*pint;

pint=(int*)data;

6
++(*pint);

void main()

char a = 'x';

int b = 1602;

increase (&a, sizeof(a));

increase (&b, sizeof(b));

printf("%c ,%d", a, b);

NULL POINTER

A NULL pointer is a regular pointer of any pointer type which has a special value that indicates
that it is not pointing to any valid reference or memory address. This value is the result of
typecasting the integer value zero to any pointer type.
int * p; p = 0; //can also write, p = NULL;
Do not confuse null pointers with void pointers. A null pointer is a value that any pointer may
take to represent that it is pointing to "nowhere", while a void pointer is a special type of
pointer that can point to somewhere without a specific type. One refers to the value stored
in the pointer itself and the other to the type of data it points to.
DYNAMIC MEMORY ALLOCATION

The exact size of array is unknown until the compile time, i.e., time when a compiler compiles
code written in a programming language into an executable form. The size of array declared
initially can be sometimes insufficient and sometimes more than required. Also, what if we
need a variable amount of memory that can only be determined during runtime? Dynamic
memory allocation allows a program to obtain more memory space, while running or to
release space when no space is required. There are 4 library functions under "stdlib.h" for
dynamic memory allocation.
malloc ()
The name malloc stands for "memory allocation". The function malloc() reserves a block of
memory of specified size and return a pointer of type void which can be casted into pointer
of any form. Syntax –
ptr=(cast-type*)malloc(byte-size)

7
Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory
with size of byte-size. If the space is insufficient, allocation fails and returns NULL pointer.
Example –
ptr=(int*)malloc(100*sizeof(int));
This statement will allocate 400(size of int=4) bytes consecutively and the pointer points to
the address of first byte of memory.
calloc ()
The name calloc stands for "contiguous allocation". The only difference between malloc() and
calloc() is that, malloc() allocates single block of memory whereas calloc() allocates multiple
blocks of memory each of same size and sets all bytes to zero. Syntax –
ptr=(cast-type*)calloc(n,element-size);
This statement will allocate contiguous space in memory for an array of n elements. For
example:
ptr=(int*)calloc(25,sizeof(int));
This statement allocates contiguous space in memory for an array of 25 elements each of size
of integer, i.e., 4 bytes.
realloc ()
If the previously allocated memory is insufficient or more than sufficient. Then, you can
change memory size previously allocated using realloc(). For example:
ptr=(int*)malloc(25*sizeof(int));
ptr=(int*)realloc(ptr,40);
First statement allocates contiguous space in memory for an array of 25 elements each of size
of integer, i.e., 4 bytes. Next statement reallocates additional 15 contiguous spaces in
memory along with the previous 25 for the new size 40.
free()
Dynamically allocated memory with either calloc() or malloc() or realloc() does not get return
on its own. The programmer must use free() explicitly to release space. Syntax – free(ptr);
This statement causes the space in memory pointer by ptr to be deallocated.
The most important difference between declaring a normal array and assigning dynamic
memory to a pointer is that the size of an array has to be a constant value, which limits its size
to what we decide at the moment of designing the program, before its execution, whereas
the dynamic memory allocation allows us to assign memory during the execution of the
program (runtime) using any variable or constant value as its size.

8
POINTERS AND INITIALIZATION

Consider the statement int *p; which declares a pointer p, and like any other variable this
space will contain garbage (random numbers), because no statement like p = &someint; has
yet been encountered which would give it a value.

Writing a statement int *p=2000; is syntactically correct as p will point to the 2000th byte of
the memory. But it might fail as byte 2000 might be being used by some other program or
may be being used by some other data type variable of the same program. So such
initialization or assignment must be avoided unless the address provided is guaranteed to be
safe.

EXERCISE

I. A pointer is a variable that stores the location of ___________ .


II. In case of int *p the * is called the operator.

III. arguments enable a function to access and change objects in the function that called
it.
IV. The void type of pointer is a special type of pointer which represents the of
type.
V. The name stands for memory allocation.

LAB WORK

I. Declare a pointer to a function that accepts three integer arguments and returns a
floating-point quantity.
II. Declare a pointer to a function that accepts three pointers to integer quantities as
arguments and returns a pointer to a floating-point quantity.
III. Write a program using pointers to read in an array of integers and print its elements
in reverse order.
IV. Write a function using pointers to add two matrices and to return the resultant matrix
to the calling function.
V. Using pointers, write a function that receives a character string and a character as
argument and deletes all occurrences of this character in the string. The function
should return the corrected string with no holes.

You might also like