Accessing characters of string

Discussion in 'C' started by FCC, May 22, 2008.

  1. FCC

    FCC New Member

    Joined:
    May 22, 2008
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0
    Hi all,

    I am brand new to C and I am having so much trouble grasping the basics of it. Consider this code:

    Code:
    char *s = "this is my string";
    printf("%s", s[3]);
    
    When I do run this code, I get this error 'Segmentation Fault." I don't really get why...I am just trying to print out like a letter from my string. I read this has to do with trying to access a part of memory that I am not allowed to access? Can anyone explain how to get around this?
     
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    Just try this
    Code:
    char *s = "this is my string";
    char c = s[3];
    printf("%s,%c", s, c);
    
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice