Doubt in pointing a variable in c.

hello friend's,
Check these codes...
#include
void main()
{
    int *x,p=4;
    x=&p;
    printf("%d",*x);
}
    
and the 2nd one goes here...
#include
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...?

Replies

  • Gurjeet Singh
    Gurjeet Singh
    mohit007kumar00
    #include
    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);
  • Sahithi Pallavi
    Sahithi Pallavi
    Just a small mistake in your program Mohit.
    See this, its working,

    #include
    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.
  • Pensu
    Pensu
    I think you cant treat a string as a single integer or character. Check this:

    #-Link-Snipped-#
  • Sahithi Pallavi
    Sahithi Pallavi
    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.
  • Gurjeet Singh
    Gurjeet Singh
    I have run the code and the above solution is working fine 😀
  • Morningdot Hablu
    Morningdot Hablu
    Thanks guy's,
    I think *str indicates c[0].So i have to use %c to print the character value but i used %s.

You are reading an archived discussion.

Related Posts

Credits :: Marco Antonio Meggiolaro Head of the RioBotz team from PUC-Rio UniversityHi friends...!!! A lot of you must be knowing about Robowars competitions being organized in almost all the...
Hello Engineers. I just need to know if it si true that the higher we get above the sea, the less TORQUE we get from a motor. I may need...
By now, most of you must have noticed the Facebook Like Box on the forum sidebar. Don't forget to hit the 'like' button.
Optimizing CrazyEngineers servers led me to discovery of things I wasn't aware of, rather, never paid much attention to their usefulness. One such thing is the "Content Delivery Network". I...
I request all crazy engineers to Please visit my website A1Tolet.com-Now Enjoy Free Advertisement of your PG,FLAT,BUNGALOW,Search For PG,FLAT,BUNGALOW,HOME.TOLET and give me your feedback because tomorrow is my project presentation...