# C++ programming



## GSquadron (Apr 17, 2012)

Hi all!
I have been reading a book about C++ and i have a very important question.
I just finished the chapter of pointers, but i didn't get the idea on
how to use them, in fact i didnt even make a single program, just kept on reading. 
(I made a lot of programs, but not advanced programs like the ones in the book)
The question is:
Keep on reading until i finish the book
or ||
Perfect pointers before going any further!

Also, the chapter was really difficult because it was using pointers with arrays and structs.
I got the idea of memory allocation though which for the book was most difficult. Any suggestion?

[Never read a book before with this kind of pleasure ]


----------



## Relinquish (Apr 17, 2012)

Right so lets see if I can help here.

So a pointer can be considered as a variable but it is one that deals in memory addresses. The whole idea of a pointer is that it points to something in memory by storing its memory location in the actual pointer. Generally a pointer takes about 32bits of memory which is always constant but it can point to anything, which can take up as much memory as possible but the point is that the amount required by a pointer is constant. 

So a pointer may be declared like so:


```
int *p_myPointer;
```

That asterisk indicates that it is a pointer. By placing 'int' before all of this doesn't make the pointer a variable of type int but it helps a pointer greatly. So I've said that it will point to something in memory. However different variables will occupy a different amount of space in memory, but how much memory does a pointer know to look at the target memory address? Well, in this case it knows an int takes up 32bits, which is 4 bytes, so it will look at 4bytes at address X.

Now, you'll run into many problems if you try to access the above pointer. Why? Because its uninitialized and doesn't have a value. Say I had an int with a value, you can give the pointer its memory address like so (assuming you have already declared it):


```
int myScore = 50;

p_myPointer = &myScore;
```

That and symbol used is the 'address of' operator and it takes the address of a variable or object and stores it in a pointer. Now that the pointer has the memory address of myScore,  it can not only access and see its value but it can also change it like so:


```
//Print to console
cout << "My score is: " << *p_myPointer << endl;

//Change value
*p_myPointer = 10;

//Reprint value
cout << "My score now is: " << *p_myPointer << endl;
```

What the asterisk does after you declare a pointer and you use it in the way I did is that is show the value pointed to by a pointer. So it shows what is stored at the memory address X. Equally this can be used to reassign values, like I did. This is known as dereferencing.

Now you can also create pointers that don't take a memory address specifically from another variable/object, but that creates variables that are the same type that the pointer points to using dynamic memory. They perform the same as an ordinary variable/object but the syntax for doing things may be different (like using the derefrerencing opperator). E.g:


```
int *p_aNewPtr = new int;
```

Whats happening is that you're declaring a variable that points to an int and using new to allocate enough memory for an int. Now you can go and give it a value:


```
*p_aNewPtr = 690;
```

If you perhaps have an array of an undetermined size when your program starts you can create one based on a variable like so:



```
int *p_aNewPtr = new int[arraySize];
```

Assuming arraySize is already declared. What was created above was a pointer to an array and the pointer gets the address of the first element. You can use the dereference operator to make life difficult but an easier way to access all the elements is to use the subscripting operator, much like the way you'd normally access an array:


```
p_aNewPtr[0] = 3;
```

When dynamically allocating memory from the heap, please remember to give the memory back when you're finished with it using the delete operator. There are two ways: for a variable and for an array like so:


```
delete p_aNewPtr;
```
or

```
delete [] p_aNewPtr;
```

I hope this has helped.


----------



## Kreij (Apr 18, 2012)

Stop and learn pointers. It is key to understanding C++ code as they are used all of the time.


----------



## Maelstrom (Apr 18, 2012)

Kreij said:


> Stop and learn pointers. It is key to understanding C++ code as they are used all of the time.



This x1000000. They're incredibly important and powerful.


----------



## GSquadron (Apr 18, 2012)

WOW
Thanks relinquish 
Looks like i will have to learn them a lot.

Also, there are the struct pointers which made me a bit of unbalanced!
like:

```
pt->name="Adam";
```

Edit: why they are so useful? I mean except memory savings?


----------



## AphexDreamer (Apr 18, 2012)

From what I learned in my Intro Class, perhaps this will be a simpler to the point example for ya. 

Lets say you have


```
int aa = 7; 
//initializes aa to 7

int *aaPointer = &aa;
```

Makes a pointer called aaPointer that points to the address of int aa which when called could be something like 0029F989. The asterix is key to declaring the variable as a pointer. Without it you couldn't direct it to the address of aa which is what & does. 
------------------------------------
Now if you were to do 


```
cout<<aaPointer; //You get the addres like 0029F989
```

but if you do 


```
cout<<*aaPointer;
```
The astrix in this case dereferences the variable aaPointer from the address it was set to point at to what is inside the address, the value 7. 

I'll add my classes PowerPoint on it for ya.

Here it is: http://www.slideshare.net/gerfeso/unit-6-pointers


----------



## Yukikaze (Apr 18, 2012)

You gotta figure out pointers, as they are an integral part for C/Cpp programming. If you need some specific help, drop me a PM with specific questions and I'll do my best to answer.


----------



## Relinquish (Apr 18, 2012)

Aleksander Dishnica said:


> WOW
> Thanks relinquish
> Looks like i will have to learn them a lot.
> 
> ...



I was a little tired last night when I wrote what I did, so I forgot to talk about structures. I also wasn't sure what you were unsure about but I think I can help now.

So the way I learnt what a structure was, it was that its like a way for a programmer to create their own variable type made up of the existing built in variable types and or possibly user defined objects and even other structures. So we may create a high score structure like so:


```
struct highScore
{
string name;
int score;
};
```

These are some of the things associated with a high score. Now if I declare a variable of type struct for a player that may use our program, we would do this:


```
highScore player1;
```

Now at this point, lets say we have his or her's score and name, how do we change the variables in the structure? Well those variables are known as fields and to access the fields we would use the period key like so:


```
player1.name = "Aleksander Dishnica";
player1.score = 500;
```

Now for a pointer to a struct. We know that a pointer will have a memory address stored in it so what we can't just do is this:


```
highScore *p_player1 = new highScore;

p_player1.name = "Aleksander Dishnica";
```

You will get a compiler error if you use a period key with an asterisk. What you need to do is get the object that the pointer is pointing to by dereferencing it and then access the fields by using the period key like:



```
(*p_player1).name = "Aleksander Dishnica";
```

There is one more elegant way of doing the last step and that is by doing this:

```
p_player1->name = "Aleksander Dishnica";
```

The '->' operator dereferences and accesses the fields of a structure or a class. 

So to answer your last question. Pointers are important because they are fast! Especially as arguments to a function.


----------



## Maelstrom (Apr 18, 2012)

Aleksander Dishnica said:


> Edit: why they are so useful? I mean except memory savings?



Dynamic memory. I've use for linked lists and binary trees, among other things. I'm sure some of the more advanced/experienced c++ programmers here could give you more reasons.


----------



## Kreij (Apr 18, 2012)

Pointers are important for passing variable into methods (function) by reference instead of by value.
Since Relinquish is doing such a fine job with example, and I just got out of bed and my caffiene levels are low, I'll let him put up an example so it's correct.


----------



## GSquadron (Apr 18, 2012)

LOL!
I was wondering... pointers are the same with java too?
Or even same with all other languages that have pointers?
Or not?


----------



## Kreij (Apr 18, 2012)

The _concept_ of pointers is the same in all languages. Their syntax, implementation and restrictions can vary depending upon the language.

How's that for being crystal clear!


----------



## stupido (Apr 18, 2012)

master the pointers and you'll master the c/c++ programming, my young padowan...


----------



## librin.so.1 (Apr 18, 2012)

From my own experience, I can say that the best way to learn using pointers is... to use pointers. Practice. Practice. Practice.
In other words - unlike many other topics, just reading about pointers doesn't help that much in learning them. To truly master pointers, use them in practice. While using them, try to think up and see as many possible uses for them as possible - as there are lots. Some that would probably never come to mind when using them _just a little_, let alone from simply reading a textbook.
Pointers are a darn powerful and useful "breed of beasts", as long as their "trainer" knows how to "train these beasts to perform exquisite tricks".

And now on the more humorous side:
Pointers can help do a lot of things. Like: making a program run faster, make some forms of code easier to write, produce segfaults, reduce memory usage, segfaults, code obfuscation, working with bare hardware, segfaults, memory manipulation, did I mention segfaults? Yes, also helps to make segfaults, just to make one's day happier! Weee!
(can't help not to also point out: This  ^____^ )

Edit: And: Yeah, what stupido said... =3


----------



## Kreij (Apr 18, 2012)

Here's a ittle to chew on Alek ...

There are three basic ways to pass arguments to functions. By value, by reference and by address.

When you pass an argument by value, a copy is created within the scope of the function and destroyed when the function terminates.

```
void foo (int a)
{
    a++;
    cout << a << endl;
}

int x = 1;

cout << x << endl;
foo(x);
cout << x << endl;

cout results...
x = 1
a = 2
x = 1
```

When you pass an argument by reference ...

```
void foo (int &a)
{
    a++;
    cout << a << endl;
}

int x = 1;

cout << x << endl;
foo(x);
cout << x << endl;

cout results ...
x = 1
a = 2
x = 2
```

Passing an argument by address ...

```
void foo (int *a)
{
    *a = 2;
}

int x = 1;
cout << x << endl;
foo (&x)
cout << x << endl;

cout results ...
x = 1
x = 2
```

This is just basic pointer stuff. It gets a lot more complicated. 


@Vinska : You forgot to mention segfaults. lol


----------



## Relinquish (Apr 18, 2012)

Kreij said:


> Passing an argument by address ...
> 
> ```
> void foo (int *a)
> ...



Well I was trying, but I couldn't give a better example. The last section of code that I highlighted above is quite significant, even though it might not look it.

Let me explain. If you pass by value, you are copying the contents of a variable to a temporary copy within a function. Depending on the size of that variable it can be a lengthy process. So something that's 24 bytes will take longer to copy than something that's 4 bytes. 4 bytes is quite small so when you pass by address using pointers, its quite quick. 

So when I say significant, I mean it in terms of performance.

All I will say about pointers is don't get carried away with them. You can end up with some nasty memory leaks. Like someone else said, practice and practice and see when it is necessary to use them.


----------



## Kreij (Apr 18, 2012)

Relinq is right, it can be extrememly significant in terms of memory use (stack) and performance.

Here's an extreme (but pretty useless) example ...

```
struct MyStruct
{
    int a;
    int b[1000000];
} myStruct;

void foo(MyStruct z, int b)
{
    z.a = b;
}

foo (myStruct, 2);
```

You just created a copy of MyStruct which includes the million int array in order to just change the value of its "a" field.


```
void foo (Mystruct *z, int b)
{
    z->a = b;
}

foo (&myStruct, 2);
```

This time you just sent the address of MyStruct to modify the field.

(I think I got the syntax right. lol This is why I use C#. It makes my brain hurt less)


----------



## librin.so.1 (Apr 18, 2012)

Kreij said:


> Relinq is right, it can be extrememly significant in terms of memory use (stack) and performance.
> 
> Here's an extreme (but pretty useless) example ...
> 
> ...



There is also one more LARGE difference:

In the first example, after changing the field a, the change "stays" in the function  - after the function finishes its execution, the said copy goes out of scope and is destroyed, leaving the value in the original copy that was passed to the function, unchanged.

In the second one, since the function is then working with the "original" copy, any modifications stay. This is very useful, when one needs that a function would "permanently" modify a variable passed to it.

P.S. Kreij, there was a small mistake in Your first example, so I edited it in the quote. I hope You don't mind.
P.P.S Also, Kreij, I think there also is a mistake in Your second example. I also edited this one in the quite.


----------



## Kreij (Apr 18, 2012)

Thanks Vinska! more than once I've beat my head against a wall trying to figure out someone else's post of code only to find they had made a error when typing. lol
Changed in my original post also.

I wans't sure about that, Vin. Dont' we need to access the derefenced pointer inside the function also?
(Like in post #15, example 3)

@Alek : Did your head explode yet? If not we can start on pointers to pointer, null pointers, void pointers and that kind of stuff.


----------



## Yukikaze (Apr 18, 2012)

Pointers to functions anyone ? 

Oh, and there is one thing to always remember regarding memory leaks (if you're on *nix):
"Be kind: Valgrind."


----------



## librin.so.1 (Apr 18, 2012)

Kreij said:


> I wans't sure about that, Vin. Dont' we need to access the derefenced pointer inside the function also?
> (Like in post #15, example 3)



We do need. But -> is a dereference operator. So, also adding a * would make it to try dereferencing an address that is the value of a. That would probably need a typecast, though. Yet, not what we need that in this case anyway.
...I got sidetracked, didn't I?

Also, to quote cplusplus.com (quote slightly modified) :


> -> is a dereference operator that is used exclusively with pointers to objects with members.


----------



## Kreij (Apr 18, 2012)

Okay you win. I'm getting page faults when trying to access C++ info in my brain.
I'm going back to my C# GPU-Z shared memory thread.


----------



## GSquadron (Apr 18, 2012)

I don't know what to say!
I can't thank you guys enough for your help


----------



## Kreij (Apr 18, 2012)

Just say you won't give up and will keep letting us help you. 
Someday you will understand that passing the knowledge you have gained to someone who is new at it, is more important and gratifying than using it.


----------



## Aquinus (Apr 18, 2012)

Kreij said:


> Someday you will understand that passing the knowledge you have gained to someone who is new at it, is more important and gratifying than using it.



That is the name of the game, my friend. All the code I write, I license GPL v3 and that is part of the reason. It's pretty cool give the world something you made and see other people make it better. I'm all for free software and the open sharing of knowledge.

http://www.gnu.org/philosophy/free-sw.html



			
				GNU-Website said:
			
		

> “Free software” means software that respects users' freedom and community. *Roughly, the users have the freedom to run, copy, distribute, study, change and improve the software. With these freedoms, the users (both individually and collectively) control the program and what it does for them.*
> 
> When users don't control the program, the program controls the users. The developer controls the program, and through it controls the users. This nonfree or “proprietary” program is therefore an instrument of unjust power.
> 
> *Thus, “free software” is a matter of liberty, not price. To understand the concept, you should think of “free” as in “free speech,” not as in “free beer”.**



*: Best statement in the entire document.


----------

