Printing a string in this weird way.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dissectcode
    New Member
    • Jul 2008
    • 66

    Printing a string in this weird way.

    Hi this is probably a stupid question, but I don't understand why the "&" prints the text (beginning at index 2 of course), isn't & an address??

    Code:
    #include <stdio.h>
    
    int main() 
    {
       char *str = "the brown fox";
       printf("what is it:  %s \n", &(str[2]));
       return 0;
    }
    result:

    what is it: e brown fox

    would it maybe be *str[2] instead?

    thank you
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Yes, the & is the address. No question of it.

    However, all of the C library uses char arrays as strings so those library functions process char arrays from the beginning to a \0 terminator. Therefore, all char addresses are assumed to be strings.

    The address of str[2] is assumed to be the start of a string.

    Comment

    • Banfa
      Recognized Expert Expert
      • Feb 2006
      • 9067

      #3
      Therefore, all char addresses are assumed to be strings.
      Strictly speaking the "%s" in the format string tells the printf function to treat the address it receives as the addresses of a char array of printable characters (i.e. a string) terminated with a '\0' character.

      If you used "%p" (correct format for a pointer) then you would get the value of the pointer.

      Not all char addresses are assumed to be strings, it is important to know if the function you are calling will be treating the address passed as a string or not and it is equally important to know if the address you are passing contains a string or not.

      Comment

      Working...