# Question concerning pointers

This topic is 4795 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi Everyone! I am just wondering why there are pointers in c++. I am trying to understand the use behind them (for example, why would someone return a pointer to a value in memory instead of returning the value itself?) For example, //returns a pointer char *read_line() { char temp[1000]; cin.getline(temp, 1000); char *res = new char[strlen(temp) + 1]; strcpy(res, temp); return res; } //returns an array of chars??? char read_line() { char temp[1000]; cin.getline(temp, 1000); char res[strlen(temp) + 1]; srcpy(res, temp); return res; } What would be the difference between the two? I'm not even sure if the latter would work... Its just an idea I had. Can someone enlighten the subject? Thanks in advance guys!

##### Share on other sites
I'll let the experts answer your question on when to use pointers. I'm still struggling with them myself. But reading your post brings up another question..

Aren't all arrays implicitely converted to a pointer when they are passed? Isn't that the reason you should always pass an integer with the size of the array along with the array (assuming you need to know the size in the function you are passing it to)?

##### Share on other sites
Quote:
 Original post by SabonisHi Everyone! I am just wondering why there are pointers in c++. I am trying to understand the use behind them (for example, why would someone return a pointer to a value in memory instead of returning the value itself?)
What if you wanted to write a function that could operate on values in arbitrary memory locations? A pointer is a memory reference mechanism; it holds a memory address.

Your second function wouldn't work, as there is no valid conversion between char [] and char. C has a complex notion of arrays, and pointers (the address of the first element in the array) are the only efficient way to manipulate them across scopes. C++ actually has object types that encapsulate arrays and can be considered atomic (and returned from functions) such as std::vector.

##### Share on other sites
From my book "As soon as an array name occurs in an expression, there is an automatic type conversion to a pointer, and the pointer will point to the first element in the array."

Another small question:

while(true)
{
//do something
}

is this not an infinite loop? I see it in so many examples of code!

But getting back to the pointers question, I'm just not understanding the specific uses of pointers besides using variables to achieve similar purposes.(Can you not make a program with normal variables that does the exact same thing as another similar function that uses pointers?)

About dealing with scopes, could you not declare a global array or would that just seem too messy?

##### Share on other sites
it is an infinite loop.
that piece of code used to confuse me as well.
normally in loops like the while (true) there is a piece of code
that'll force a break out of the loop. either a function or break;

when you take a data structures class you'll understand all the reasons for pointers. for now, just be curious and poke around some more but except that they are necessary.

##### Share on other sites
Here is an expample.

Model myBigFatModel;

Render(myBigFatModel);
//This function here is going to make a copy of your model and then send the copy to the Render function. Your model could be a few megabytes huge! Where as if you were passing by pointer, you would only pass the address of the model which takes only 4 bytes on 32-bit systems.

Render(*myBigFatModel);
//Only sends 4 bytes.

There are quite a few other uses of pointers but i dont have the time to explain it now. Just understand what a pointer is and how it works.
If you cant find a use for them now, dont use them. In time there will be situations where you will see the need to use them.

##### Share on other sites
Quote:
 Original post by HughGAren't all arrays implicitely converted to a pointer when they are passed? Isn't that the reason you should always pass an integer with the size of the array along with the array (assuming you need to know the size in the function you are passing it to)?
Well, the answer is complicated. See, there's actually an array type of sorts in C, but it's not user-accessible. Base type, array type and array length together constitute the type of an array, but that information does not survive scope transition (passing the array to a function). Consequently, the name of the array alone serves as a shorthand for the address of the first element, which is the "implicit conversion to pointer" you speak of.

Also because all the rich type information of a C array does not survive scope transition, it is necessary to either pass the length of the array or find some means of indicating the array termination, which results in null-terminated character arrays as the C representation of a string. Finally, this is the reason why sizeof(arr)/sizeof(arr[0]) does not yield the array length outside of the scope in which it was declared.

##### Share on other sites
Quote:
 Original post by SabonisFrom my book "As soon as an array name occurs in an expression, there is an automatic type conversion to a pointer, and the pointer will point to the first element in the array."
Many instructional books, sadly, are over-genericized. This is because these concepts are not simple, and can not be taught in a linear progression from zero to hero. They require a significant amount of retreading to fully grasp. In short, take what most books tell you as a "good enough" explanation.

Quote:
 But getting back to the pointers question, I'm just not understanding the specific uses of pointers besides using variables to achieve similar purposes.
Consider the following code:
char * func(char * p, char * q){  while(*p++ = *q++)    ;  return p;}
Why does it work? What does it do? How do you propose doing the same without pointers? [All left as an exercise for the readers. Function and variable names stripped of semantic commentary. I'm off to bed!]

##### Share on other sites
Hmmm That makes a lot more sense now.. Ok thanks again! Feel free to comment more if you wish.... The more the info the better!

##### Share on other sites
Quote:
 char * func(char * p, char * q){ while(*p++ = *q++) ; return p;}Why does it work? What does it do? How do you propose doing the same without pointers? [All left as an exercise for the readers. Function and variable names stripped of semantic commentary. I'm off to bed!]

Hmmm... A char is an 8 byte value so I am not sure what will happen whenever p or q reaches 255. Does it wrap back around to 0 when it reaches 255? If so then this loop would go on forever...

##### Share on other sites
You mean 8-bit, and I don't really want to get into the pedantry there...

Anyway. The key thing you need to note is that although individual characters are being assigned, the pointers are being incremented.

Also, a while loop continues until its condition in brackets evaluates false. 0 is false.

Note that the condition uses an assignment, not an equality operator. The assignment will evaluate to the value being assigned, so when 0 is assigned, the loop breaks out.

Note that there is nothing inside the body of the loop.

Now trace through it again, carefully, and understand what it does. Draw yourself a little picture of memory, and put some chars at some locations, and char*'s 'p' and 'q' pointing to them, somewhere else.

##### Share on other sites
Quote:
 Original post by HughGHmmm... A char is an 8 byte value so I am not sure what will happen whenever p or q reaches 255. Does it wrap back around to 0 when it reaches 255? If so then this loop would go on forever...
You're barking up the wrong tree. Remember, pointers contain addresses, and ++ takes precedence over *.

##### Share on other sites
Pointers are a huge topic, and understanding them can take a long period of time. When I was learning C++, I just didn't see the use of them. Indeed, I assumed pointers were totally replacable by regular variables by different implementations.
However, I though functions were just as useless as I didn't see what the problem was with copying and pasting where normal people would call functions :P.

Now, all I can say is hang on there. Just learn them no matter how useless they seem. You can't understand what's the "point of pointers" if you don't know what they are, but you don't really know what pointers are until you learn their point [smile].

Anyways, try to learn a little assembly. You'll immediately understand what is going on under the hood. You'll learn a lot about how memory works in computers. And once you learn how the computer stores stuff, you'll immediately understand what pointers are.

The many uses of pointers are beyond what one could type in a post. I'm not sure how your book is structured, but chances are, you haven't learned classes, or other advanced topics. The more you learn, the more uses you'll see of pointers.

##### Share on other sites
Quote:
 Original post by ZahlmanYou mean 8-bit,

Yes, my mistake.

Quote:
 and I don't really want to get into the pedantry there...

Huh?

Quote:
 Anyway. The key thing you need to note is that although individual characters are being assigned, the pointers are being incremented. Also, a while loop continues until its condition in brackets evaluates false. 0 is false.Note that the condition uses an assignment, not an equality operator. The assignment will evaluate to the value being assigned, so when 0 is assigned, the loop breaks out.

Yes I noticed it was assignment. I just thought that no matter what you assigned it to, it would always evaluate to true (E.G. while(a=3) always evaluates to true). I thought if it was a=0 then it would evaluate if a was actually 0 instead of a. Tested it this morning and turns out I was wrong. It's confusing coming from Java where only booleans can be inside the paranthesis.

Quote:
 You're barking up the wrong tree. Remember, pointers contain addresses, and ++ takes precedence over *.

Ahh, pointer arithmetic. I'll give it another shot.

##### Share on other sites
Quote:
 Original post by HughGYes I noticed it was assignment. I just thought that no matter what you assigned it to, it would always evaluate to true (E.G. while(a=3) always evaluates to true). I thought if it was a=0 then it would evaluate if a was actually 0 instead of a. Tested it this morning and turns out I was wrong. It's confusing coming from Java where only booleans can be inside the paranthesis.
In C, any non-zero value evaluates as true. What if(a = q) does is first assign the value of q to a, then test the resultant value of a for truth.

##### Share on other sites
char * func(char * p, char * q)
{
while(*p++ = *q++)
;
return p;
}

1. The code copies the character obtained at memory location q into the space at memory location p.
2. Then increments the addresses at q and p by one.
3. Copies the character at q to p.
4. Repeats this process until the nul terminating character at q is reached.

##### Share on other sites
Correct (step 3 is a repetition of step 1, of course). The effect is to copy a null-terminated character array, the C representation of a string.