Thread: Help me undersstand structs

  1. #1
    Registered User
    Join Date
    Apr 2015
    Posts
    180

    Help me undersstand structs

    Why do we use &Elem->ID and &Elem->name? With & we are storing in the address of the pointer that is on the heap. Then what is the -> all about? Why not use a dot like &Elem.id?

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    
    
    typedef struct
    {
        int id;
        char name[80];
        int mark;
    }STUDENT;
    
    STUDENT *CreateElement()
    {
    
    STUDENT *Elem;
    Elem=(STUDENT *)malloc(sizeof(STUDENT));
    if(Elem==NULL)
       return NULL
    printf("ID = ");
    scanf("%d", &(Elem->id)); 
    printf("Name = ");
    printf("\n");
    fgets(&(Elem->name), 80, stdin);    
    
    }
    Last edited by telmo_d; 05-11-2015 at 03:24 AM.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,667
    > Then what is the -> all about?
    Because you have a pointer to a struct - a pointer to the memory you got back from malloc.

    > Why not use a dot like &Elem.id?
    You would use the dot form if you have a variable of that type.

    Consider.
    Code:
    STUDENT s;
    STUDENT *ps = malloc(sizeof(*ps));
    
    // read into s
    scanf("%d", &s.id); 
    
    // read into ps (both are the same)
    scanf("%d", &ps->id); 
    scanf("%d", &(*ps).id); // use the dot form, but only because of all the extra syntax around ps
    
    // you can even use array notation
    scanf("%d", &ps[0].id);
    The arrow notation is just the least cumbersome of the possible ways of getting from a pointer-to-struct to the actual data element within the struct.
    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: 2
    Last Post: 01-08-2013, 07:55 AM
  2. Typedef Structs inside Typdef structs
    By gremory in forum C Programming
    Replies: 21
    Last Post: 12-30-2011, 07:48 PM
  3. [ noob question ] Help with structs within structs
    By Riverfoot in forum C Programming
    Replies: 3
    Last Post: 04-26-2011, 07:24 PM
  4. Passing Structs Into An Array Of Structs.
    By TheTaoOfBill in forum C Programming
    Replies: 3
    Last Post: 10-07-2010, 09:38 AM
  5. passing structs & pointers to structs as arguments
    By Markallen85 in forum C Programming
    Replies: 6
    Last Post: 03-16-2004, 07:14 PM