Thread: is a string in C = pointer = array?

  1. #1
    Registered User
    Join Date
    Feb 2010
    Posts
    32

    is a string in C = pointer = array?

    If I have a function that consumes a string,
    for example,

    Code:
    void myFunction (char *s) {
    
    ...
    
    }
    
    Can I treat s as a array?
    so, s[0] will give me a character?
    same as s[2]...etc?
    
    and s[null] will give me \0?

  2. #2
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    Basically yeah. Though there is no s[null]...

    Lets say you have this code:
    Code:
    char* s = "abc";
    A string will be stored in memory. You will have 4 memory locations with values 'a','b','c','\0'. All strings in C are null terminated, where '\0' is the null character (which is the same with zero). Now, the pointer s points at the first element. So it points at 'a'. As you know you can get 'a' by doing
    Code:
    *s;
    Now lets say you want 'b'. An easy way to get it is use indexes and do
    Code:
    s[1];
    if you know about pointer arithmetic that would be the same by doing
    Code:
    *(s+1);
    and in general
    Code:
    s[i] == *(s+i)
    So what indexes do are give you the character that is shown X amount of elements after where the pointer points, where X is the index (like s[X]).

    Note that a pointer can change value which makes it different than a C-array. In the above example you could do
    Code:
    s = s + 2;
    Now, s points at 'c'. If you do
    Code:
    s[1];
    you will get the next character from where s points at. Which is now '\0'.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. sorting number
    By Leslie in forum C Programming
    Replies: 8
    Last Post: 05-20-2009, 04:23 AM
  2. String issues
    By The_professor in forum C++ Programming
    Replies: 7
    Last Post: 06-12-2007, 09:11 AM
  3. RicBot
    By John_ in forum C++ Programming
    Replies: 8
    Last Post: 06-13-2006, 06:52 PM
  4. Something is wrong with this menu...
    By DarkViper in forum Windows Programming
    Replies: 2
    Last Post: 12-14-2002, 11:06 PM