simple Pointer initialization

前端 未结 7 1760
傲寒
傲寒 2020-12-13 07:14

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;
         


        
相关标签:
7条回答
  • 2020-12-13 08:15

    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.

    0 讨论(0)
提交回复
热议问题