Dereferencing pointers without pointing them at a variable

Posted by Miguel on Stack Overflow See other posts from Stack Overflow or by Miguel
Published on 2013-06-25T10:14:18Z Indexed on 2013/06/25 10:21 UTC
Read the original article Hit count: 316

Filed under:
|

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) unless you either malloc'd space for it (p = malloc(x)), or set it to the address of another variable (p = &a)

However in this code, the first assignment works consistently, while the last one causes a segfault:

typedef struct
{
    int value;
} test_struct;

int main(void)
{
    //This works
    int* colin;
    *colin = 5;

    //This never works
    test_struct* carter;
    carter->value = 5;
}

Why does the first one work when colin isn't pointing at any spare memory? And why does the 2nd never work?

I'm writing this in C, but people with C++ knowledge should be able to answer this as well.

© Stack Overflow or respective owner

Related posts about c

    Related posts about pointers