by Dan East » Jul 26, 2001 @ 6:26pm
Okay, I think don't think you have a good grasp of pointers. Let's look at a contrived chunk of memory:<br>[fixed]0x1000 'M' 'y' ' ' 'T' 'e' 'x' 't' '/0'[/fixed]<br><br>In this case we are using a byte to store a letter (which is ANSI / ASCII). So if we look at the byte at memory address 0x1000 we will see it has a value of 77 (remember that all a byte is is a number from 0 to 255). 77 is the ASCII value for M. If we look at the byte at memory location 0x1001 we get 121, which is y. Now in your example you have a pointer to a character, so in our example it would point to the 'M' character:<br>[fixed]char *pTest="My Text";[/fixed]<br>Now all pTest is is a number that refers to a memory location. So in this example pTest has a value of 0x1000, which is the address of the first byte of the string. If we want to see what the actual value is at memory location 0x1000 then we use the indirection operator like so:<br>[fixed]if (*pText=='M') WhatDanSaysIsTrue=TRUE;[/fixed]<br>And...<br>[fixed]if ((int)pText==0x1000) WhatDanSaysIsTrue=TRUE;[/fixed]<br>In the above line I am treating pText like the number it really is, and checking to see if it is pointing to the memory address 0x1000. Now if I perform any math to pText, I only affect the number that the pText pointer is:<br>[fixed]pText+=3;[/fixed]<br>So pText was 0x1000, I incremented it by 3, and since a char is 1 byte, pText's numerical value is incremented by 3*1. So pText is 0x1003. If we look at our memory block above, we see that:<br>[fixed]*pText=='T';[/fixed]<br>What we did has nothing to do with changing the memory that contains the string. We just changed the value of a pointer that happens to point to that memory block.<br><br>Also, neither C nor C++ perform any type of memory management for you. If you don't delete or free it, then it is still there. Other languages like Java try to keep track of what data still has references to it and free what is not used. Don't confuse that with variable scope, which is where you declare a variable in a particular code block or function, and try to use it after it goes out of scope. In that case the data will have been reused by some other variable that is now in scope, and bad things may happen. Here is an example:<br>[fixed]char *MyFunction() {<br> char szText[10]="Testing";<br> return szText;<br>}[/fixed]<br>That function returns a pointer to the string szText. Well szText will be out of scope outside that function, so the data will not be valid. In that case you would either allocate the data with new or malloc and return that, or you could declare szText as static, which makes sure it hangs around, or you could create a global variable, which will be around as long as the program is running.<br><br>Dan East