simple Pointer initialization


It has been a while that I used pointers and I just wanna quickly check how I can initialize an integer pointer?

a) int *tmpPtr = 0;

b) int *tmpPtr = null;

c) int a = 0;
   int *tmpPtr = &a;


Thanks for all your answers so far. The funny thing is, that if I intitalize the pointer as follows, then the mem::copy operation works fine.

int tmp = 0;
int *tmpPtr = &tmp;
Mem::Copy((void*)tmpPtr, basepointer(), sizeof(int));

However, if I do it like this:

int *tmpPtr = 0;
Mem::Copy((void*)tmpPtr, basepointer(), sizeof(int));

then I get a crash during mem::copy...


3/12/2016 4:49:22 PM

Simple questions are fine, I think it's well established that SO is meant to be for all levels, not just an elite.

There is no null in C (unless you define it yourself). Initializing to a null pointer can be done in one of the following two ways:

int *p = 0;
int *p = NULL;

If you dereference p after that, you're likely to get an access violation (I believe it's undefined behavior according to the standard, so really, anything could happen, up to and including, total annihilation of the universe - it may even continue to run fine, but I wouldn't rely on it).

To get a pointer to a real integer, just use:

int a = 7;
int *p = &a;

using the address-of operator.

Re your edit, it's not weird at all, you just need to visualize it. Let's pretend that all variables are created starting at memory location 100 and integers and pointers are both 4 bytes in length. Breaking your two situations down to their simplest form:

                                  int x = 2;
int *px = 0;                      int *px = &x;

         +-----+                          +-----+
px(100): |   0 |                  x(100)  |   2 |
         +-----+                          +-----+
                                  px(104) | 100 |

Then you execute the command

*px = 7;

in an attempt to change the variable pointed to by px.

On the left-hand side, you will try to write the value 7 to memory location 0. That's a bad thing; very few systems will allow you to do that without crashing, even fewer will allow it without any adverse effects at all (some versions of HP-UX actually worked okay).

On the right side is what should happen. The value picked up from px is 100, so the value 7 is written to that memory location, changing x as intended.

I often find pictures (even primitive ASCII art ones, since I'm no Rubens or Botticelli) help clarify the concepts. Hopefully it's cleared it up a little for you.

9/4/2009 1:24:35 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow