structure and pointer

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • askcq
    New Member
    • Mar 2007
    • 63

    structure and pointer

    #include <stdio.h>

    typedef struct exam ex;
    struct exam {
    int val;
    };

    int main() {
    int aa;
    ex user;
    ex *ex_ptr;

    printf("\n value ");
    scanf("%d", &(ex_ptr->val));
    ex_ptr = &user;
    printf("%d",*(i nt *)aa= (ex_ptr->val));

    }

    iam trying to assign the value "val" to the integer aa.
    But segmentation fault arises ...pls help
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    On line 14 you are using ex_ptr before you put an address in it:

    [code=c]
    scanf("%d", &(ex_ptr->val));
    [/code]

    Comment

    • askcq
      New Member
      • Mar 2007
      • 63

      #3
      yes changed it ...but again the same error occurs

      Comment

      • gpraghuram
        Recognized Expert Top Contributor
        • Mar 2007
        • 1275

        #4
        HI,
        Allocate memory for the pointer and the call scanf.
        Code:
        ex *ex_ptr=(struct exam*)malloc(sizeof(struct exam)); ///Add this line
        
        printf("\n value ");
        scanf("%d", &(ex_ptr->val));
        Thanks
        Raghuram

        Comment

        • askcq
          New Member
          • Mar 2007
          • 63

          #5
          yes....but still it shows error ...

          Comment

          • weaknessforcats
            Recognized Expert Expert
            • Mar 2007
            • 9214

            #6
            Originally posted by askcq
            yes....but still it shows error ...
            Not when I ran this code:
            [code=c]
            ex *ex_ptr=(struct exam*)malloc(si zeof(struct exam)); ///Add this line

            printf("\n value ");
            scanf("%d", &(ex_ptr->val));
            printf("You entered %d\n", ex_ptr->val);

            }
            [/code]

            Comment

            Working...