Quick actions

cmd+k|ctrl+k

Navigation

Languages

Pointer

Snippet info

Language

C

Visibility

public

Author

menghsiu

Created

2019-04-08T17:56:36Z

Updated

2019-04-09T00:23:35Z

#include <stdio.h>

struct rectangle {
    int height;
    int width;
};

int main(void) {   
    struct rectangle rec_a;
    struct rectangle *rec_b;
    struct rectangle *rec_c;
    int address;    
    void* pointer;
    
    //another example worth looking into
    int a = 50;
    int *p = &a;
    int *pp = (int *)&p;
    
    rec_a.height = 10;                                                    
    rec_a.width = 20;                                                                                         
                                                                                                          
    //point to rec_a                                               
    rec_b = &rec_a;                                               
    //point to rec_b                                             
    pointer = rec_b;                                             
                                                       
    printf("rec_a(0x%x), rec_b(0x%x), pointer(0x%x)\n", &rec_a, rec_b, pointer);
    printf("rec_a width(%d) height(%d)\n", rec_a.width, rec_a.height);
    printf("rec_b width(%d) height(%d)\n", rec_b->width, rec_b->height);
    printf("pointer width(%d) height(%d)\n", ((struct rectangle *)pointer)->width, ((struct rectangle *)pointer)->height);
                                                                      
    address = rec_b;                          
    printf("address(0x%x)\n", address); //a memory stores the address of rec_a
                                                      
    rec_c = (struct rectangle *)address;              
    printf("rec_c(0x%x)\n", rec_c);    
    
    //segmentation fault
    // printf("rec_c width(%d) height(%d)\n", rec_c->width, rec_c->height);                

    //another sample worth look into
    printf ("%d", *((int *)(*pp)));
    
    return 0;                                    
}                                               
INFO