Doubt in pointing a variable in c.

Morningdot Hablu
@morningdot-6Xuj4M โ€ข Oct 21, 2024

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...?

Replies

Welcome, guest

Join CrazyEngineers to reply, ask questions, and participate in conversations.

CrazyEngineers powered by Jatra Community Platform

  • Gurjeet Singh

    @gurjeet-LUX7B1 • Jan 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);

  • Sahithi Pallavi

    @sahithi-oJZaYj • Jan 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.

  • Pensu

    @pensu-8tNeGU • Jan 11, 2011

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

    #-Link-Snipped-#

  • Sahithi Pallavi

    @sahithi-oJZaYj • Jan 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.

  • Gurjeet Singh

    @gurjeet-LUX7B1 • Jan 11, 2011

    I have run the code and the above solution is working fine ๐Ÿ˜€

  • Morningdot Hablu

    @morningdot-6Xuj4M • Jan 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.