CrazyEngineers
  • Doubt in pointing a variable in c.

    Morningdot Hablu

    Morningdot Hablu

    @morningdot-6Xuj4M
    Updated: Oct 21, 2024
    Views: 880
    hello friend's,
    Check these codes...
    #include<stdio.h>
    void main()
    {
        int *x,p=4;
        x=&p;
        printf("%d",*x);
    }
        
    
    and the 2nd one goes here...
    #include<stdio.h>
    void main()
    {
        char c[]="mohit kumar singh";
        char *str;
        str=&c;
        printf("%s",*str);
    }    
    
    from the first program i got the output "4".
    But don't know why 2nd one will show an Segmentation fault.
    Can anyone tell me the reason for this Segmentation fault...?
    0
    Replies
Howdy guest!
Dear guest, you must be logged-in to participate on CrazyEngineers. We would love to have you as a member of our community. Consider creating an account or login.
Replies
  • Gurjeet Singh

    MemberJan 10, 2011

    mohit007kumar00
    #include<stdio.h>
    void main()
    {
        char c[]="mohit kumar singh";
        char *str;
        str=&c;
        printf("%s",*str);
    }    
    
    i think you are going to be reading in a valid memory address from the user may be it has already allocated
    try to use this --

    char *str=malloc(sizeof(char)*250);
    scanf(" %c ", str);
    Are you sure? This action cannot be undone.
    Cancel
  • Sahithi Pallavi

    MemberJan 11, 2011

    Just a small mistake in your program Mohit.
    See this, its working,

    #include<stdio.h>
    void main()
    {
    char c[]="mohit kumar singh";
    char *str;
    str=c;
    printf("%s",str);
    }




    Output : mohit kumar singh
    that is percentage s in printf statement.
    Are you sure? This action cannot be undone.
    Cancel
  • Pensu

    MemberJan 11, 2011

    I think you cant treat a string as a single integer or character. Check this:

    #-Link-Snipped-#
    Are you sure? This action cannot be undone.
    Cancel
  • Sahithi Pallavi

    MemberJan 11, 2011

    As per my Knowledge, Segmentation fault occurs if there is any fault in accessing the memory address. If we tried to access the invalid or wrong memory address, then the Segmentation Fault error occurs.
    Are you sure? This action cannot be undone.
    Cancel
  • Gurjeet Singh

    MemberJan 11, 2011

    I have run the code and the above solution is working fine 😀
    Are you sure? This action cannot be undone.
    Cancel
  • Morningdot Hablu

    MemberJan 11, 2011

    Thanks guy's,
    I think *str indicates c[0].So i have to use %c to print the character value but i used %s.
    Are you sure? This action cannot be undone.
    Cancel
Home Channels Search Login Register