Dereferencing pointers without pointing them at a variable

前端 未结 4 1288
野趣味
野趣味 2020-12-02 01:14

I\'m having trouble understanding how some pointers work. I always thought that when you created a pointer variable (p), you couldn\'t deference and assign (*p = value) unle

4条回答
  •  攒了一身酷
    2020-12-02 02:06

    // This works
    int* colin;
    *colin = 5;
    

    Welcome to undefined behavior: the fact that it does not crash does not mean that it works. Accessing uninitialized pointer is always wrong, yet sometimes it does not crash.

    couldn't deference and assign unless you either malloc'd space for it or set it to the address of another variable

    This is correct. In general, you need to point your pointer to some place that has been allocated to your program. There are multiple ways of doing that, but they all boil down to one of the two scenarios that you describe - the pointer is pointed either to a dynamically allocated memory (i.e. malloc), or to statically allocated memory (i.e. a variable).

提交回复
热议问题