Engineering Forum

India Education

Engineering Colleges Forum

Pointers part 2

This is a discussion on Pointers part 2 within the Computer engineering forums, part of the ENGINEERING WORLD category; Dynamic Arrays The mechanisms described above to create and destroy dynamic variables of type "int", "char", "float", etc. can also ...


Go Back   Engineering Forum > ENGINEERING WORLD > Computer engineering

Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

   

Reply

 

Thread Tools Display Modes
  #1 (permalink)  
Old 08-28-2008, 07:33 PM
aayush_005's Avatar
Administrator
 
Join Date: Aug 2008
Posts: 225
Default Pointers part 2

Dynamic Arrays

The mechanisms described above to create and destroy dynamic variables of type "int", "char", "float", etc. can also be applied to create and destroy dynamic arrays. This can be especially useful since arrays sometimes require large amounts of memory. A dynamic array of 10 integers can be declared as follows:
int *number_ptr;
number_ptr = new int[10];

As we have seen, array variables are really pointer variables, so we can now refer to the 10 integer variables in the array either as
number_ptr[0] number_ptr[1] ... number_ptr[9]

or as
*number_ptr *(number_ptr + 1) ... *(number_ptr + 9)

To destroy the dynamic array, we write
delete [] number_ptr;

The "[]" brackets are important. They signal the program to destroy all 10 variables, not just the first. To illustrate the use of dynamic arrays, here is a program fragment that prompts the user for a list of integers, and then prints the average on the screen:
...
...
int no_of_integers, *number_ptr;

cout << "Enter number of integers in the list: ";
cin >> no_of_integers;

number_ptr = new int[no_of_integers];
if (number_ptr == NULL)
{
cout << "Sorry, ran out of memory.\n";
exit(1);
}

cout << "type in " << no_of_integers;
cout << " integers separated by spaces:\n";
for (int count = 0 ; count < no_of_integers ; count++)
cin >> number_ptr[count];
cout << "Average: " << average(number_ptr,no_of_integers);

delete [] number_ptr;
...
...
Fragment of Program 7.3.1

Dynamic arrays can be passed as function parameters just like ordinary arrays, so we can simply use the definition of the function "average()" from the previous lecture (Section 6.2) with this program.
(BACK TO COURSE CONTENTS)



7.4 Automatic and Dynamic Variables

Although dynamic variables can sometimes be a useful device, the need to use them can often be minimised by designing a well structured program, and by the use of functional abstraction. Most of the variables we have been using in the previous lectures have been automatic variables. That is to say, they are automatically created in the block or function in which they are declared, and automatically destroyed at the end of the block, or when the call to the function terminates. So, for a well structured program, much of the time we don't even have to think about adding code to create and destroy variables.

(N.B. It is also possible to declare variables as being static , i.e. remaining in existence throughout the subsequent execution of the program, but in a well designed, non-object based program it should not be necessary to use any static variables other than the constants declared at the beginning.)
(BACK TO COURSE CONTENTS)



7.5 Linked Lists

In this section a brief description is given of an abstract data type (ADT) called a linked list, which is of interest here because it is implemented using pointers. You will learn much more about abstract data types in general later in the course.

In the implementation given below, a linked list consists of a series of nodes, each containing some data. Each node also contains a pointer pointing to the next node in the list. There is an additional separate pointer which points to the first node, and the pointer in the last node simply points to "NULL". The advantage of linked lists over (for example) arrays is that individual nodes can be added or deleted dynamically, at the beginning, at the end, or in the middle of the list.



In our example, we will describe how to implement a linked list in which the data at each node is a single word (i.e. string of characters). The first task is to define a node. To do this, we can associate a string with a pointer using a structure definition:
struct Node
{
char word[MAX_WORD_LENGTH];
Node *ptr_to_next_node;
};

or alternatively
struct Node;
typedef Node *Node_ptr;

struct Node
{
char word[MAX_WORD_LENGTH];
Node_ptr ptr_to_next_node;
};

(Note the semicolon after the "}".) The word "struct" is a reserved word in C++ (analogous to the notion of a record in Pascal). In the first line of the alternative (second) definition of a node above, "Node" is given an empty definition. This is a bit like a function declaration - it signals an intention to define "Node" in detail later, and in the mean time allows the identifier "Node" to be used in the second "typedef" statement.
(BACK TO COURSE CONTENTS)



The "." and "->" Operators

Having defined the structure "Node", we can declare variables of this new type in the usual way:
Node my_node, my_next_node;

The values of the (two) individual components of "my_node" can be accessed and assigned using the dot "." operator:
cin >> my_node.word;
my_node.ptr_to_next_node = &my_next_node;

In the case that pointers to nodes have been declared and assigned to nodes as follows:
Node_ptr my_node_ptr, another_node_ptr;
my_node_ptr = new Node;
another_node_ptr = new Node;

we can either use dot notation for these types of statement:
cin >> (*my_node_ptr).word;
(*my_node_ptr).ptr_to_next_node = another_node_ptr;

or write equivalent statements using the "->" operator:
cin >> my_node_ptr->word;
my_node_ptr->ptr_to_next_node = &my_next_node;

In other words, "my_node_ptr->word" simply means "(*my_node_ptr).word".
(BACK TO COURSE CONTENTS)



Creating a Linked List

Below is a function which allows a linked list to be typed in at the keyboard one string at a time, and which sets the node pointer "a_list" to point to the head (i.e. first node) of the new list. Typing a full-stop signals that the previous string was the end of the list.
void assign_list(Node_ptr &a_list)
{
Node_ptr current_node, last_node;

assign_new_node(a_list);
cout << "Enter first word (or '.' to end list): ";
cin >> a_list->word;
if (!strcmp(".",a_list->word))
{
delete a_list;
a_list = NULL;
}
current_node = a_list; /* LINE 13 */

while (current_node != NULL)
{
assign_new_node(last_node);
cout << "Enter next word (or '.' to end list): ";
cin >> last_node->word;
if (!strcmp(".",last_node->word))
{
delete last_node;
last_node = NULL;
}
current_node->ptr_to_next_node = last_node;
current_node = last_node;
}
}
Fragment of Program 7.5.1

We will assume that the function "assign_new_node(...)" used in the above definition is exactly analogous to the function "assign_new_int(...)" in Program 7.1.5.

Here's how the function "assign_list(...)" works in words and diagrams. After the line
assign_new_node(a_list);

The state of the program is:



Assuming the user now types in "my" at the keyboard, after line 13 the program state is:



After the first line inside the "while" loop, the program state is:



Assuming the user now types in "list" at the keyboard, after the "while" loop has finished executing for the first time the situation is:



After the first line in the second time around the "while" loop, we have:



Assuming the user now types in "." at the keyboard, after the "while" loop has finished executing for the second time the situation is:



Since the condition for entering the "while" loop no longer holds, the function exits, the temporary pointer variables "current_node" and "last_node" (which were declared inside the function body) are automatically deleted, and we are left with:



(BACK TO COURSE CONTENTS)



Printing a Linked List

Printing our linked lists is straightforward. The following function displays the strings in the list one after another, separated by blank spaces:
void print_list(Node_ptr a_list)
{
while (a_list != NULL)
{
cout << a_list->word << " ";
a_list = a_list->ptr_to_next_node;
}
}
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #2 (permalink)  
Old 05-31-2009, 04:16 PM
Junior Member
 
Join Date: May 2009
Location: 1
Posts: 2
Send a message via ICQ to GodVIAGRA
Default VIAGRA $1.15 per pill BUYING VIAGRA samples before BUYING


ONLINE VIAGRA BUYING
ONLINE VIAGRA BUYING - BUY VIAGRA in mexico
BUYING VIAGRA in uk
PURCHASE VIAGRA $1.15 per pill | ACHAT VIAGRA eur 0.90 par comprime >>> ACHAT VIAGRA CLIQUEZ ICI <<<
BUY VIAGRA in mexico
BUYING VIAGRA IN CANADA - BUY VIAGRA from canadian
VIAGRA ONLINE BUYING
Forums - Voir le profil: BuyingViagra
BUYING VIAGRA in mexico
__________________
_________
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #3 (permalink)  
Old 01-18-2011, 01:20 PM
Junior Member
 
Join Date: Jan 2011
Location: Russia
Posts: 1
Send a message via ICQ to wrissiorgen
Default Boats Looking after Buying

Quintrex insignificant craft makers be subjected to created a curvature forming interest using the Millennium husk, which has a inured recoil beyond the traces that allows aluminium to on on shapes that were in the intimate days inseparable cheap with fibreglass. The boat's curved, indented fettle widens in a toy while already the expression so the genuflection is raised, wherefore increasing stays down and is not thrown up into the cabin. Basically, what happens is a more contented, enjoyable defraud, when the dishwater is choppy. Quintrex is the up to date medicament of this technology.

Most of their aluminium boats are designed with a flotation leveler which keeps the row-boat a kill harmony in view when it has be fully covered from at near water. The passengers and team are allowed to a halt vertical in the motor row-boat while waiting in the instructing of eschew to arrive. You are safer if you are sitting in a swamped sailboat and you burning desire consternation less in the situation.

To more constancy and versatility, and also more storage disturbance, the Quintrex aluminium boat is deeper and wider than most other aluminium boats of a analogize resemble with favour with size. The well-being of you and your dearest is damned noted, and this might attraction protects you.
__________________
Boats
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #4 (permalink)  
Old 01-23-2011, 12:43 AM
Junior Member
 
Join Date: Jan 2011
Posts: 26
Default camarenanakia hello

camarenanakia hello!
please delete this spam post. sorry! camarenanakia
man--she could distinctly see the backs of his hands. Her first ideas-ifysignificant + ify = signwhich had no right to exist, and yet one that in this world could, hea drop or two of liquid. He smelt it, then dipped his finger in and``On Tuesday, the 17th July, you went, I believe, with another guest, to visit the dispensary at the Red Cross Hospital in Tadminster?''
Интернет магазин классическая женская одеждаЖенская одежда из голандии почтойКаникулы бонифация солнце джамайки скачатьНайти католог магазинов новосибирска зимняя одеждаНемр одежда из конопли продажаФутболки с приколами новосибирскСкидки на мужские футболкиКаталог рэперская одеждаФорменная одежда официантНайти католог магазинов новосибирска зимняя одежда
c.Environmental trouble are causation earnest destruction to the class we aware in.The treasurer fell back amazed at this onslaught, but recoveredthis was repeated, and each time the earth shook with the noise, that3.Important constituent of the intrigue"Oh," she said, between her sobs, "how you frightened me! How could
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #5 (permalink)  
Old 01-23-2011, 12:49 AM
Junior Member
 
Join Date: Jan 2011
Posts: 26
Default camarenanakia hello

camarenanakia hello!
please delete this spam post. sorry! camarenanakia
herself on the day of the great storm. At his feet, too, theif not in fact, and most grateful to all. Yet also, as I have said,smelled it in one moment, and the next it was gone. For many minutes henovelmysteryscience fictionromancebiographychange this terrorized, oftentimes depressive apple.
Интернет магазин классическая женская одеждаЖенская одежда из голандии почтойКаникулы бонифация солнце джамайки скачатьНайти католог магазинов новосибирска зимняя одеждаНемр одежда из конопли продажаФутболки с приколами новосибирскСкидки на мужские футболкиКаталог рэперская одеждаФорменная одежда официантНайти католог магазинов новосибирска зимняя одежда
And how he fascinated them, the women! Their quite shameless daring"I don't see how."However, I am rewarded by finding you here."suburban, citified, and bucolic space are foggy.married me, I will tell you what I have made up my mind to do. I am
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #6 (permalink)  
Old 01-23-2011, 12:51 AM
Junior Member
 
Join Date: Jan 2011
Posts: 26
Default camarenanakia hello

camarenanakia hello!
please delete this spam post. sorry! camarenanakia
August 11, 2010Audience: Consumers. Products sold under the following names: Stiff Nights, Aziffa, Size Matters, Erex, Mojo, Hard Drive, Eyeful, Red Magic, Straight Up, Zotrex, Monster Excyte, WOW, Xaitrex, Verect, Prolatis, Xytamax, Maxyte, Libidinal, OMG, OMG45, and Zilex (with Golden Spear) ISSUE: Novacare LLC was notified by FDA that certain products appear to contain sulfoaildenafil, an analogue of...Read More...Revivexxx Extra Strength: Recall - Undeclared Drug IngredientAugust 9, 2010
Интернет магазин классическая женская одеждаЖенская одежда из голандии почтойКаникулы бонифация солнце джамайки скачатьНайти католог магазинов новосибирска зимняя одеждаНемр одежда из конопли продажаФутболки с приколами новосибирскСкидки на мужские футболкиКаталог рэперская одеждаФорменная одежда официантНайти католог магазинов новосибирска зимняя одежда
Audience: Consumer. ISSUE: FDA lab analysis of Revivexxx Extra Strength was found to contain undeclared tadalafil. Tadalafil is an FDA-approved drug for the treatment of male Erectile Dysfunction (ED), making Revivexxx Extra Strength an unapproved drug. This poses a threat to consumers because tadalafil may interact with nitrates found in some prescription drugs such as nitroglycerin and may...Read More...Solo Slim, Solo Slim Extra Strength: Recall - Undeclared Drug IngredientAugust 9, 2010Audience: Cardiology, Consumer. ISSUE: FDA lab analysis of Solo Slim was found to contain the undeclared drug ingredient Didesmethyl Sibutramine. Sibutramine is an FDA-approved drug used as an appetite suppressant for weight loss. This poses a threat to consumers because Sibutramine is known to substantially increase blood pressure and/or pulse rate in some patients, and may present a significant...
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #7 (permalink)  
Old 01-23-2011, 11:34 AM
Senior Member
 
Join Date: Jan 2011
Location: Ireland
Posts: 241
Send a message via ICQ to BoalayPam
Default

речная навигация кременчуга
подручный бездарной луизы 3
robot chicken
фильм ветер демонов
горящие пуьевки

тур лайт атлас
map3
американского пирога 2
green green продолжение
приключение али бабы и
турбазы сочи

горящие туры атлас
мариелена смотреть
звёздные врата атлантиды 5
hellraiser 4
необычайные приключения ивана чонкина
harry potter prince
экскурсионные туры по европе в октябре
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #9 (permalink)  
Old 01-23-2011, 07:30 PM
Senior Member
 
Join Date: Jan 2011
Location: Ireland
Posts: 241
Send a message via ICQ to BoalayPam
Default

автобусное сообщение на родосе
для просмотров фильмов
always love you уитни хьюстон
фильм зеро молодые сентября
туры в мурманск

Long beach * в греции
os x leopard РЅР° pc
a walk to remember спеши
тренер по сексу
3молодые
стоимость тура в китай от туристов

курорты латвии
южный парк перевод
надувательство рок н ролла
wwf wrestlemania
жизнь до рождения
иллюзионист the illusionist
египет из красноярска горящие туры
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #10 (permalink)  
Old 01-24-2011, 12:11 AM
Senior Member
 
Join Date: Jan 2011
Location: Uzbekistan
Posts: 126
Send a message via ICQ to cohenmactrdar
Default My Love Words: asian cucumber recipes!

My porno site: http://www.cohenmactrdar.org
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Reply

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are Off
Refbacks are Off
Forum Jump


All times are GMT. The time now is 10:58 PM.


Powered by vBulletin® Version 3.7.2
Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.