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

Programming Fundamentals Manual 09

Programming Fundamentals Lab Manual 9 Covers topics about pointers in C Department of Electrical Engineering University of Engineering and Technology Lahore 2016

Uploaded by

2017ee184
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Programming Fundamentals Manual 09

Programming Fundamentals Lab Manual 9 Covers topics about pointers in C Department of Electrical Engineering University of Engineering and Technology Lahore 2016

Uploaded by

2017ee184
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Lab Manual

Programming

9 Fundamentals
Department of Electrical Engineering
University of Engineering and Technology Lahore 2016
Instructors: Umer Shahid, Miss Sana Javed

Name
Registration Number _
Procedure:

1. Students should read the manual before coming to lab.


2. In the lab, students should complete Labs 8.1 through 8.7 in sequence. Your instructor
will give further instructions as to grading and completion of the lab.

Purpose:

1. To understand the concept of pointers in C


2. To learn how to define pointers and how to use dynamic memory allocation

Introduction to Pointers:

A pointer is a variable which contains the address in memory of another variable. We can have a
pointer to any variable type. The unary or monadic operator & gives the “address of a variable”.
The indirection or dereference operator * gives the contents of an object pointed to by a pointer''.
To declare a pointer to a “variable” do:

int *pointer;

Pointers in C are easy and fun to learn. Some C programming tasks are performed more easily
with pointers, and other tasks, such as dynamic memory allocation, cannot be performed
without using pointers. So it becomes necessary to learn pointers to become a perfect C
programmer. Let's start learning them in simple and easy steps.

1 EE-Semester 2 (Spring 2018)


Department of Electrical Engineering
University Of Engineering and Technology Lahore
As you know, every variable is a memory location and every memory location has its address
defined which can be accessed using ampersand (&) operator, which denotes an address in
memory.

What are Pointers?


A pointer is a variable whose value is the address of another variable, i.e., direct address of the
memory location. Like any variable or constant, you must declare a pointer before using it to
store any variable address. The general form of a pointer variable declaration is −

type *var_name;

Here, type is the pointer's base type; it must be a valid C data type and var_name is the name
of the pointer variable. The asterisk * used to declare a pointer is the same asterisk used for
multiplication. However, in this statement the asterisk is being used to designate a variable as a
pointer. Take a look at some of the valid pointer declarations −

int *ip; /* pointer to an integer */


double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */

The actual data type of the value of all pointers, whether integer, float, character, or otherwise,
is the same, a long hexadecimal number that represents a memory address. The only difference
between pointers of different data types is the data type of the variable or constant that the
pointer points to.

How to Use Pointers?


There are a few important operations, which we will do with the help of pointers very
frequently. (a) We define a pointer variable, (b) assign the address of a variable to a pointer
and (c) finally access the value at the address available in the pointer variable. This is done by
using unary operator * that returns the value of the variable located at the address specified by
its operand. The following example makes use of these operations –

Example 8.2: Compile and execute the following code on your machine and
explain its output?

#include <stdio.h>

2 EE-Semester 2 (Spring 2018)


Department of Electrical Engineering
University Of Engineering and Technology Lahore
int main () {

int var = 20; /* actual variable declaration */

int *ip; /* pointer variable declaration */

ip = &var; /* store address of var in pointer variable*/

printf("Address of var variable: %x\n", &var );

/* address stored in pointer variable */

printf("Address stored in ip variable: %x\n", ip );

/* access the value using the pointer */

printf("Value of *ip variable: %d\n", *ip );

return 0;

NULL Pointers
It is always a good practice to assign a NULL value to a pointer variable in case you do not
have an exact address to be assigned. This is done at the time of variable declaration. A pointer
that is assigned NULL is called a null pointer. The NULL pointer is a constant with a value of
zero defined in several standard libraries.

In most of the operating systems, programs are not permitted to access memory at address 0
because that memory is reserved by the operating system. However, the memory address 0 has
special significance; it signals that the pointer is not intended to point to an accessible memory
location. But by convention, if a pointer contains the null (zero) value, it is assumed to point to
nothing.

To check for a null pointer, you can use an 'if' statement as follows −

if(ptr) /* succeeds if p is not null */


if(!ptr) /* succeeds if p is null */

3 EE-Semester 2 (Spring 2018)


Department of Electrical Engineering
University Of Engineering and Technology Lahore
Dynamic Memory Allocation:

It is also possible to initialize pointers using free memory. This allows dynamic allocation of
memory. It is useful for setting up structures such as linked lists or data trees where you don't
know exactly how much memory will be needed at compile time, so you have to get memory
during the program's execution. We'll look at these structures later, but for now, we'll simply
examine how to request memory from and return memory to the operating system.

The function malloc, residing in the stdlib.h header file, is used to initialize pointers with
memory from free store (a section of memory available to all programs). malloc works just like
any other function call. The argument to malloc is the amount of memory requested (in bytes),
and malloc gets a block of memory of that size and then returns a pointer to the block of memory
allocated.

Since different variable types have different memory requirements, we need to get a size for the
amount of memory malloc should return. So we need to know how to get the size of different
variable types. This can be done using the keyword sizeof, which takes an expression and returns
its size. For example, sizeof(int) would return the number of bytes required to store an integer.
#include <stdlib.h>

int *ptr = malloc( sizeof(int) );

This code set ptr to point to a memory address of size int. The memory that is pointed to
becomes unavailable to other programs. This means that the careful coder should free this
memory at the end of its usage lest the memory be lost to the operating system for the duration of
the program (this is often called a memory leak because the program is not keeping track of all of
its memory).

Note that it is slightly cleaner to write malloc statements by taking the size of the variable
pointed to by using the pointer directly:
int *ptr = malloc( sizeof(*ptr) );

What's going on here? sizeof(*ptr) will evaluate the size of whatever we would get back from
dereferencing ptr; since ptr is a pointer to an int, *ptr would give us an int, so sizeof(*ptr) will
return the size of an integer. So why do this? Well, if we later rewrite the declaration of ptr the
following, then we would only have to rewrite the first part of it:
float *ptr = malloc( sizeof(*ptr) );

We don't have to go back and correct the malloc call to use sizeof(float). Since ptr would be
pointing to a float, *ptr would be a float, so sizeof(*ptr) would still give the right size!

This becomes even more useful when you end up allocating memory for a variable far after the
point you declare it:
float *ptr;
/* hundreds of lines of code */
ptr = malloc( sizeof(*ptr) );

4 EE-Semester 2 (Spring 2018)


Department of Electrical Engineering
University Of Engineering and Technology Lahore
The free function returns memory to the operating system.
free( ptr );

After freeing a pointer, it is a good idea to reset it to point to 0. When 0 is assigned to a pointer,
the pointer becomes a null pointer, in other words, it points to nothing. By doing this, when you
do something foolish with the pointer (it happens a lot, even with experienced programmers),
you find out immediately instead of later, when you have done considerable damage.

Arithmetic of Pointers:

Pointers have many but easy concepts and they are very important to C programming. The
following important pointer concepts should be clear to any C programmer. A pointer in c is an
address, which is a numeric value. Therefore, you can perform arithmetic operations on a
pointer just as you can on a numeric value. There are four arithmetic operators that can be used
on pointers: ++, --, +, and -

To understand pointer arithmetic, let us consider that ptr is an integer pointer which points to
the address 1000. Assuming 32-bit integers, let us perform the following arithmetic operation
on the pointer −

ptr++

After the above operation, the ptr will point to the location 1004 because each time ptr is
incremented, it will point to the next integer location which is 4 bytes next to the current
location. This operation will move the pointer to the next memory location without impacting
the actual value at the memory location. If ptr points to a character whose address is 1000, then
the above operation will point to the location 1001 because the next character will be available
at 1001.

Incrementing a Pointer
We prefer using a pointer in our program instead of an array because the variable pointer can be
incremented, unlike the array name which cannot be incremented because it is a constant
pointer. The following program increments the variable pointer to access each succeeding
element of the array –

Example 8.2: Compile and execute the following code on your machine and
explain its output?

5 EE-Semester 2 (Spring 2018)


Department of Electrical Engineering
University Of Engineering and Technology Lahore
#include <stdio.h>

const int MAX = 3;

int main () {

int var[] = {10, 100, 200};

int i, *ptr;

/* let us have array address in pointer */

ptr = var;

for ( i = 0; i < MAX; i++) {

printf("Address of var[%d] = %x\n", i, ptr );

printf("Value of var[%d] = %d\n", i, *ptr );

/* move to the next location */

ptr++;

return 0;

Pointer Comparisons
Pointers may be compared by using relational operators, such as ==, <, and >. If p1 and p2 point
to variables that are related to each other, such as elements of the same array, then p1 and p2
can be meaningfully compared.

The following program modifies the previous example − one by incrementing the variable
pointer so long as the address to which it points is either less than or equal to the address of the
last element of the array, which is &var[MAX - 1] –

6 EE-Semester 2 (Spring 2018)


Department of Electrical Engineering
University Of Engineering and Technology Lahore
Example 8.3: Compile and execute the following code on your machine and
explain its output?

#include <stdio.h>

const int MAX = 3;

int main () {

int var[] = {10, 100, 200};

int i, *ptr;

/* let us have address of the first element in pointer */

ptr = var;

i = 0;

while ( ptr <= &var[MAX - 1] ) {

printf("Address of var[%d] = %x\n", i, ptr );

printf("Value of var[%d] = %d\n", i, *ptr );

/* point to the previous location */

ptr++;

i++;

return 0;

Passing Pointers to function:

C programming allows passing a pointer to a function. To do so, simply declare the function
parameter as a pointer type.

7 EE-Semester 2 (Spring 2018)


Department of Electrical Engineering
University Of Engineering and Technology Lahore
Following is a simple example where we pass an unsigned long pointer to a function and
change the value inside the function which reflects back in the calling function –

The function, which can accept a pointer, can also accept an array as shown in the following
example –

Example 8.4: Compile and execute the following code on your machine and
explain its output?

#include <stdio.h>

/* function declaration */

double getAverage(int *arr, int size);

int main () {

/* an int array with 5 elements */

int balance[5] = {1000, 2, 3, 17, 50};

double avg;

/* pass pointer to the array as an argument */

avg = getAverage( balance, 5 ) ;

/* output the returned value */

printf("Average value is: %f\n", avg );

return 0;

double getAverage(int *arr, int size) {

int i, sum = 0;

double avg;

for (i = 0; i < size; ++i) {

8 EE-Semester 2 (Spring 2018)


Department of Electrical Engineering
University Of Engineering and Technology Lahore
sum += arr[i];

avg = (double)sum / size;

return avg;

Lab assignment:
 Read out the manual very carefully, there will be a viva in which each student will be
asked details of this manual individually.

9 EE-Semester 2 (Spring 2018)


Department of Electrical Engineering
University Of Engineering and Technology Lahore

You might also like