Sunday, January 23, 2011

"self describing" char pointer example



This program really drives home what's happening. Big ups to Matt for explaining this.

The output:

The string mainZ points to is Test123
The addy contained in mainZ is 004030BD
The addy OF mainZ is 0028FF0C

Now we call the function to alter mainZ

The string localZ points to is Ipsum Lorem
The addy contained in localZ in local function is 00403024
The addy OF localZ in local function is 0028FEF0

The string mainZ points to is Ipsum Lorem
The addy contained in mainZ is 00403024
The addy OF mainZ is 0028FF0C

So you can see here that the address of the char pointer variable mainZ (as in, where mainZ is) stays the same. Good. The address that mainZ points to is first 004030BD, and then it takes on the address contained in localZ, 00403024.

The most important thing I've learned (again, big ups to Matt) is that the idea that initialized space in memory that happens in a local function is NOT destroyed. It can get LOST if you don't let a pointer outside of the function know where it is, but it's not magically deleted. I'm still plowing through the books I have looking for something that explicitly states that. Everything I read always says rather plainly that data outside of a local function is not accessible. This is true for named variables (like localZ) it seems, but not for assigned spots in memory, like the address of where a string literal starts.

Hopefully I can just look at the program next time I get confused!

No comments:

Post a Comment