Thread: Looking help to understand Pointer to structure

  1. #1
    Registered User
    Join Date
    May 2021
    Posts
    66

    Looking help to understand Pointer to structure

    I have been trying to understand Pointer to structure for a long time But even after spending a lot of time on google search it. I don't understand it. I hope somebody help me

    What I don't understand, I will tell you through the program given bellow.

    Code:
    #include<stdio.h>
    
    #include<stdlib.h>
    
    
    struct STRUCTURE 
    {
        int X ;
    };
    
    
    int main ()
    {
        struct STRUCTURE *POINTER = malloc(sizeof(*POINTER)); /* Allocate dyanamic memory */
        
        POINTER -> X = 20; 
        
        return 0;
    }
    In the program , I have declared the structure above the main function.

    In main function there is pointer to structure I think malloc function allocate address and store in variable POINTER.

    Pointer is used to hold the address of another variable.

    The variable POINTER, Whose address of another variable does it store ?

    How many address malloc function allocate ?

    Thank you
    Rahul

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    There is only one address returned by malloc, but it is the start address of however many bytes you asked for, as given by your sizeof() expression.

    This is the same thing without the malloc.
    Code:
    struct STRUCTURE myvar;
    struct STRUCTURE *POINTER = &myvar;
    POINTER -> X = 20;  // actually sets myvar.X
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 5
    Last Post: 08-04-2017, 07:42 AM
  2. Help for understand pointer
    By redred in forum C Programming
    Replies: 8
    Last Post: 01-19-2013, 01:41 PM
  3. Replies: 9
    Last Post: 06-13-2009, 02:31 AM
  4. Trying to Understand Structure
    By jamez05 in forum C Programming
    Replies: 3
    Last Post: 09-28-2006, 11:44 AM

Tags for this Thread