C++ Question

Started by
9 comments, last by Brerick 21 years, 2 months ago
I don''t see why pointers are necissary or how to use them. Can anyone explain in laymans terms how to use them? I have read the section in my book over and over, but I just can''t get it. When I say pointers I mean: *. I might have the wrong word, if i do, i am sorry. I am still a newb. Thanks for your time.
Advertisement
You know I am in that same boat, man. I don''t know how to use pointers well, but I DO KNOW that they can transfer large amounts of data, like structs or classes. They are more stable than passing parameters. In fact, the use of a pointer is "POINTING" the data to an object. FOR EXAMPLE: KEYS -> HOUSE. This lame example would be if you had two structures "KEYS" and "HOUSE" the pointer would be the variable "YOU" made up to pass the data from "KEYS" to the "HOUSE." Like so: KEYS -> YOU -> HOUSE. So basically the "YOU" pointer does the work and not the entire structure house. Does this help?

-TAylor
EMAIL: music_dreamer@hotmail.com
Taylor G.
Well, the general idea of pointers is to ''point'' (sorry for my bad English ) to something.
As you possibly read in the book, pointers give you the ability to address the variable/object.
The general way to use them is:
1. you declare your usual variable as

  int a = 0;  

2. When you need a pointer, you declare it like:

  int *iPtr;  


So, here we came to the idea of changing variables by reference, which you achieve like this:

  iPtr = &a // make iPtr point to the ''i'' variable*iPtr = 10; // here you are changing the value that iPtr is pointing to, i.e ''i''// So that now your ''i'' variable will be not 0, as at the beginning, but 10.  


I would recommend that you go around the web and find more tutorials on pointers, since there is a HUGE amount of information can be found on this topic.
Check out those websites:
http://www.cprogramming.com
http://programmers-heaven.com
htp://www.planet-source-code.com
And of course, this website..

Good luck.


" Do we need us? "


Ionware Productions - Games and Game Tools Development

Pointers are usually used for implementing linked lists also, right? If so, I''d definitely consider that useful. =)

This isn''''t life in the fast lane, it''''s life in the oncoming traffic.
-- Terry Pratchett
Over the centuries, mankind has tried many ways of combating the forces of evil...prayer,fasting, good works and so on. Up until Doom, no one seemed to have thought about thedouble-barrel shotgun. Eat leaden death, demon... -- Terry Pratchett
From our very own Gamedev article section:

A Tutorial on Pointers and Arrays in C (read this one first),

and

Understanding Pointers: A Game Developer''s Approach.

Enjoy!!!
Firstly, arrays are nothing more than pointers. You just can't change the memory location they point to. So this:
char name[] = "Steve";
is pretty much the same as this:
char * name2 = "Steve";

Remember, an array simply points to the memory location of the first element. A pointer does the same, except you can change name2 to point to the 't' in Steve like this
name2++; // add one element to the pointer
// name++; wouldn't work work;

But why don't you just use regular arrays if they're practically the same thing? I don't need to point to 't' in Steve...

Well, let's say you have a program that stores the names of people and the salary they make in a data-structure. But you have no idea how many elements there will be. It could be 10, it could be 100, or even 1000. You don't want to declare 10,000 elements when you probably won't need them. You can't do this either:
int numberOfPeople = 0;
cout << "How many people will you be entering? ";
cin >> numberOfPeople;
NameSalary people[numberOfPeople]; // won't compile!

The array can only have a fixed size. Enter on-the-fly memory allocation. The above code becomes this:
int numberOfPeople = 0;
cout << "How many people will you be entering? ";
cin >> numberOfPeople;
NameSalary * people = NULL; // it doesn't point to anything, so be explicit about it.
people = new NameSalary[numberOfPeople];

and you can go through the people pointer like an array:
for(int i = 0; i < numberOfPeople; i++) {
// do stuff, like enter the info, or print the info
}

EDIT: When done, you have to get rid of the memory
delete [] people; // the brackets are only used when you created an array

There are many other things pointers can do, but this is one of the simplist and is used very often.

[edited by - nobodynews on January 29, 2003 11:53:19 PM]

C++: A Dialog | C++0x Features: Part1 (lambdas, auto, static_assert) , Part 2 (rvalue references) , Part 3 (decltype) | Write Games | Fix Your Timestep!

pointers are the same as passing-by-reference. Instead of passing an entire structure to a function you can just tell it where to look for it (i.e. you give the function a reference to your data)
"Voilà! In view, a humble vaudevillian veteran, cast vicariously as both victim and villain by the vicissitudes of Fate. This visage, no mere veneer of vanity, is a vestige of the vox populi, now vacant, vanished. However, this valorous visitation of a bygone vexation stands vivified, and has vowed to vanquish these venal and virulent vermin vanguarding vice and vouchsafing the violently vicious and voracious violation of volition. The only verdict is vengeance; a vendetta held as a votive, not in vain, for the value and veracity of such shall one day vindicate the vigilant and the virtuous. Verily, this vichyssoise of verbiage veers most verbose, so let me simply add that it's my very good honor to meet you and you may call me V.".....V
quote:Original post by nobodynews
Firstly, arrays are nothing more than pointers.

A common misconception, one that is exacerbated by the ambiguity of array syntax. Arrays are NOT the same as const pointers. They are totally different things.

quote:
You just can't change the memory location they point to. So this:
char name[] = "Steve";
is pretty much the same as this:
char * name2 = "Steve";


No it isn't. The first statement is an array declaration and initialization. The second is a pointer initialization to an entry in the string table. "name[0] = 's'" will work on the first statement, but may not on the second.

When you use an array as a pointer, you're really doing an implicit cast from an array to a pointer. So it's an easy mistake to make, and one that a disturbingly large percentage of beginning and intermediate programmers make.

Don't listen to me. I've had too much coffee.

[edited by - sneftel on January 30, 2003 1:50:52 PM]
Even though it was probably already said in all the other replies, I'm going to say it again. (I think I'm pretty good at explaining it)

-----

Pointers are a variable type...

If something is defined "char a", or "int b" a pointer is no different than saying "pointer c". Its a type of a variable that holds a memory address. On 32 bit operating system, its 4 bytes (32 bits). Its really no different than declaring something as a "long d" (thats also 4 bytes/32bits)

Memory on your 32-bit computer is linear, from byte 0 to byte 4.2 billion. In a nice long row.

Pointers are good for "pointing" to a memory location.

Simple so far, right?

----

Now to answer the question on why would you use them.

Let's say inside your program you need to create address book files. You know : name, address, phone number...

(I'm going to assume you know structs already)

struct AddressFile{ char name[50]; char address[50]; char phone[50];};AddressFile Book[50];  


Instead of saying you can have a max of 50 records, you want it unlimited.

How would you declare that? Normally arrays in C/C++ require a number.

You use a pointer

AddressFile *Book;  


Now, this might be confusing. The name is "*Book" but its declared as an AddressFile. I've already said that a pointer is a 4 byte/32bit variable. So how can that hold an unlimited size of AddressFile structs which is 150 bytes each into the 4 byte pointer?

I'll tell you.

Book = new AddressFile[50];  


Lets look at that closer... Book is a pointer that holds 4 bytes to a place in memory. The new command is creating us memory of type AddressFile with the length of 50 long. Its kinda of like saying in english: "I need to create a place in memory to hold my AddressFiles, I need 50 of them." The new command will do it, and return the pointer where this memory is found on your computer. Then you can use the Book pointer like any other variable.

Keep in mind, the new command creates memory. You must also delete it to prevent memory leaks. When you are done using your Book, "delete []Book" That tells the computer to free the memory that you requested.

The [] is empty because the new command knew the size of the memory it created... The new command hides the size somewhere hidden, the delete does not have to pass the size.

----

You can also use a variable with the new command to specify a buffer size.

int Count = 2000;Book = new AddressFile[Count]; 


----

You might have been thinking, if a pointer is just a pointer. Why is it declared with a type infront instead of just being called "pointer *book"

Its done for math purposes only.

Lets say you see the code

Book++;  


What would that do? A pointer is just a 32 bit number. Like a long. If I add one to it, it will point to the memory location +1...

Thats where the type comes in. If you Book++, you are not actually increasing the pointer + 1... You are increasing the pointer + sizeof(AddressBook) or pointer + 150 bytes (the size of address book)... Thats all that does.

----

Now whats the "&" for... Thats address of. That is returning me the pointer of where that variable is in memory...

Lets say you want to read an address file from an actual file on your computer.

Lets say you read in 1 record that is in a char[150]... Enough to fit into your AddressFile struct. But its in the the buffer of char[150]... Technically they are the same. But you need to move it into your AddressFile struct.

char filerecordbuffer[150];AddressFile *Book;Book = new AddressFile[50];// readin the file and fillout filerecordbuffermemcpy(Book[0], &filerecordbuffer[0], sizeof(AddressFile));// do stuffdelete []Book;  


That will copy sizeof(AddressFile) (or 150 bytes) into Book position 0, starting from location &filerecordbuffer[0]... Or "the pointer of the first byte of filerecordbuffer" It just moves 150 bytes from one position into another position, really.

And blam! Its in the array at position 0.

Ok. I hope that helps some. I gotta get back to work.

[edited by - JoeyBlow2 on January 30, 2003 2:01:03 PM]
----

Functions...

void function1(void){  AddressFile *book;  Book = new AddressFile[50];  ChangeName(book, 20, "JoeyBlow"); }void ChangeName(AddressFile *book, long position, char*name){  strcpy(book[position]->name,name);}    


If you don't use pointers, you would create a local copy of AddressFile when calling ChangeName, not actually change the memory that function1 is using.

Also. Why did the struct now use -> instead of just a normal . (dot)... Its for clarity, to let you know you are changing someone elses memory, not memory local to your own function. If you wanted to change it to be more consistant, you change the function to be :

void ChangeName(AddressFile &book, long position, char*name){  strcpy(book[position].name,name);}    


Use the & instead of *... That says pass that paramter by pointer, but use the older syntax... Now you access book like you would with a normal . (dot)

----

Now I never did make the Book unlimited in size. I always typed in a size anyways. But with enough knowledge of pointers, you could make it unlimited....

void Function1(void){AddressFile *Book;long Count = 1;Book = new AddressFile[Count];IncreaseSize(Book, &Count);printf("The size of book is now %d", Count);delete []Book;}void IncreaseSize(AddressFile *Book, long *Count){ AddressFile *temp; *Count++; temp = new AddressFile[*Count]; memcpy(temp, Book, sizeof(AddressFile) * (*Count-1)); delete []Book; Book = temp;}   


See!

[edited by - JoeyBlow2 on January 30, 2003 2:06:06 PM]

[edited by - JoeyBlow2 on January 30, 2003 2:07:29 PM]

[edited by - JoeyBlow2 on January 30, 2003 2:08:20 PM]

This topic is closed to new replies.

Advertisement