Sunteți pe pagina 1din 11

Data Structures and Algorithms

Lab 1

What are Pointers?


A pointer is a variable whose value is the address of another variable. Like any variable or
constant, you must declare a pointer before you can work with it. 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++ type and var-name is the name of the
pointer variable. The asterisk you used to declare a pointer is the same asterisk that you use for
multiplication. However, in this statement the asterisk is being used to designate a variable as a
pointer. 

int *ip; // pointer to an integer


char *ch // pointer to 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.
Null Pointer:
If you do not know the exact address to be assigned to a pointer Null value should be
assigned to it. 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, including iostream. Consider the following program 
#include <iostream>

using namespace std;


int main () {
int *ptr = NULL;
cout << "The value of ptr is " << ptr ;

return 0;
}
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
Pointers vs Arrays:
Pointers and arrays are strongly related. In fact, pointers and arrays are interchangeable in
many cases.  A pointer that points to the beginning of an array can access that array by
using either pointer arithmetic or array-style indexing.
#include <iostream>

using namespace std;


Data Structures and Algorithms
Lab 1

const int MAX = 3;

int main () {
int var[MAX] = {10, 100, 200};
int *ptr;

// let us have array address in pointer.


ptr = var;

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


cout << "Address of var[" << i << "] = ";
cout << ptr << endl;

cout << "Value of var[" << i << "] = ";


cout << *ptr << endl;

// point to the next location


ptr++;
}

return 0;
}

Passing Pointers to Functions in C++:


C++ allows you to pass a pointer to a function. To do so, simply declare the function
parameter as a pointer type.
#include <iostream>
#include <ctime>

using namespace std;


void getSeconds(unsigned long *par);

int main () {
unsigned long sec;
getSeconds( &sec );

// print the actual value


cout << "Number of seconds :" << sec << endl;

return 0;
}

void getSeconds(unsigned long *par) {


// get the current number of seconds
*par = time( NULL );
Data Structures and Algorithms
Lab 1

return;
}
Passing array as function argument:
#include <iostream>
using namespace std;

// 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


cout << "Average value is: " << avg << endl;

return 0;
}

double getAverage(int *arr, int size) {


int i, sum = 0;
double avg;

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


sum += arr[i];
}
avg = double(sum) / size;

return avg;
}

Structures:
C/C++ arrays allow you to define variables that combine several data items of the same
kind, but structure is another user defined data type which allows you to combine data
items of different kinds.

Defining a Structure
To define a structure, you must use the struct statement. The struct statement defines
a new data type, with more than one member, for your program. The format of the
struct statement is this. For example, to define a book structure
struct Books {
Data Structures and Algorithms
Lab 1

char title[50];
char author[50];
char subject[100];
int book_id;
} book;

Accessing Structure Members


To access any member of a structure, we use the member access operator (.). The
member access operator is coded as a period between the structure variable name
and the structure member that we wish to access. You would use struct keyword to
define variables of structure type. Following is the example to explain usage of
structure.
#include <iostream>
#include <cstring>

using namespace std;

struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};

int main() {
struct Books Book1; // Declare Book1 of type Book
struct Books Book2; // Declare Book2 of type Book

// book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;

// book 2 specification
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;

// Print Book1 info


cout << "Book 1 title : " << Book1.title <<endl;
cout << "Book 1 author : " << Book1.author <<endl;
cout << "Book 1 subject : " << Book1.subject <<endl;
cout << "Book 1 id : " << Book1.book_id <<endl;
Data Structures and Algorithms
Lab 1

// Print Book2 info


cout << "Book 2 title : " << Book2.title <<endl;
cout << "Book 2 author : " << Book2.author <<endl;
cout << "Book 2 subject : " << Book2.subject <<endl;
cout << "Book 2 id : " << Book2.book_id <<endl;

return 0;
}

Structures as Function Arguments


You can pass a structure as a function argument in very similar way as you pass any
other variable or pointer. You would access structure variables in the similar way as
you have accessed in the above example
#include <iostream>
#include <cstring>

using namespace std;


void printBook( struct Books book );

struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};

int main() {
struct Books Book1; // Declare Book1 of type Book
struct Books Book2; // Declare Book2 of type Book

// book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;

// book 2 specification
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;

// Print Book1 info


printBook( Book1 );

// Print Book2 info


printBook( Book2 );
Data Structures and Algorithms
Lab 1

return 0;
}
void printBook( struct Books book ) {
cout << "Book title : " << book.title <<endl;
cout << "Book author : " << book.author <<endl;
cout << "Book subject : " << book.subject <<endl;
cout << "Book id : " << book.book_id <<endl;
}

Pointers to Structures
You can define pointers to structures in very similar way as you define pointer to any
other variable as follows −
struct Books *struct_pointer;
Now, you can store the address of a structure variable in the above defined pointer
variable. To find the address of a structure variable, place the & operator before the
structure's name as follows −
struct_pointer = &Book1;
To access the members of a structure using a pointer to that structure, you must use
the -> operator as follows −
struct_pointer->title;
Let us re-write above example using structure pointer, hope this will be easy for you to
understand the concept 
#include <iostream>
#include <cstring>

using namespace std;


void printBook( struct Books *book );

struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main() {
struct Books Book1; // Declare Book1 of type Book
struct Books Book2; // Declare Book2 of type Book

// Book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Data Structures and Algorithms
Lab 1

Book1.book_id = 6495407;

// Book 2 specification
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;

// Print Book1 info, passing address of structure


printBook( &Book1 );

// Print Book1 info, passing address of structure


printBook( &Book2 );

return 0;
}

// This function accept pointer to structure as parameter.


void printBook( struct Books *book ) {
cout << "Book title : " << book->title <<endl;
cout << "Book author : " << book->author <<endl;
cout << "Book subject : " << book->subject <<endl;
cout << "Book id : " << book->book_id <<endl;
}

Problems:

1. Write a program to add, subtract and multiply two complex numbers using
structures to function.
2. Write a structure to store the name, account number and balance of customers
(more than 10) and store their information.
a) Write a function to print the names of all the customers having balance less
than $200.
b) Write a function to add $100 in the balance of all the customers having more
than $1000 in their balance and then print the incremented value of their balance.

Self Referential Structures


Self Referential structures are those structures that have one or more pointers which
point to the same type of structure, as their member.
In other words, structures pointing to the same type of structures are self-referential in
nature.
struct node {
int data1;
char data2;
Data Structures and Algorithms
Lab 1

struct node* link;


};
int main()
{
struct node ob;
return 0;
}
In the above example ‘link’ is a pointer to a structure of type ‘node’. Hence, the structure
‘node’ is a self-referential structure with ‘link’ as the referencing pointer.
An important point to consider is that the pointer should be initialized properly before
accessing, as by default it contains garbage value.
Types of Self Referential Structures
1. Self Referential Structure with Single Link
2. Self Referential Structure with Multiple Links
Self Referential Structure with Single Link: These structures can have only one self-
pointer as their member. The following example will show us how to connect the
objects of a self-referential structure with the single link and access the corresponding
data members. The connection formed is shown in the following figure.

#include <stdio.h>
struct node {
int data1;
char data2;
struct node* link;
};
int main()
{
struct node ob1; // Node1
// Intialization
ob1.link = NULL;
ob1.data1 = 10;
ob1.data2 = 20;

struct node ob2; // Node2

// Initialization
ob2.link = NULL;
ob2.data1 = 30;
ob2.data2 = 40;

// Linking ob1 and ob2


Data Structures and Algorithms
Lab 1

ob1.link = &ob2;

// Accessing data members of ob2 using ob1


printf("%d", ob1.link->data1);
printf("\n%d", ob1.link->data2);
return 0;
}

Problem:
Declare a self referential structure tNode as follows:

struct tNode {int data; tNode *next;};

Create 5 objects of tNode class at system stack. Link the nodes with one another in a long chain through
next pointer. Try it and test node data through first node object.

Self Referential Structure with Multiple Links: Self referential structures with multiple links
can have more than one self-pointers. Many complicated data structures can be easily
constructed using these structures. Such structures can easily connect to more than one nodes
at a time. The following example shows one such structure with more than one links.

#include <stdio.h>
struct node {
int data;
struct node* prev_link;
struct node* next_link;
};
int main()
{
struct node ob1; // Node1
// Intialization
ob1.prev_link = NULL;
ob1.next_link = NULL;
ob1.data = 10;
Data Structures and Algorithms
Lab 1

struct node ob2; // Node2

// Intialization
ob2.prev_link = NULL;
ob2.next_link = NULL;
ob2.data = 20;

struct node ob3; // Node3

// Intialization
ob3.prev_link = NULL;
ob3.next_link = NULL;
ob3.data = 30;

// Forward links
ob1.next_link = &ob2;
ob2.next_link = &ob3;

// Backward links
ob2.prev_link = &ob1;
ob3.prev_link = &ob2;

// Accessing data of ob1, ob2 and ob3 by ob1


printf("%d\t", ob1.data);
printf("%d\t", ob1.next_link->data);
printf("%d\n", ob1.next_link->next_link->data);

// Accessing data of ob1, ob2 and ob3 by ob2


printf("%d\t", ob2.prev_link->data);
printf("%d\t", ob2.data);
Data Structures and Algorithms
Lab 1

printf("%d\n", ob2.next_link->data);

// Accessing data of ob1, ob2 and ob3 by ob3


printf("%d\t", ob3.prev_link->prev_link->data);
printf("%d\t", ob3.prev_link->data);
printf("%d", ob3.data);
return 0;
}

S-ar putea să vă placă și