Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Array of pointers question

  1. Oct 20, 2008 #1
    in this code i got a chat type pointer which is an array
    who consists out of 4 char cells

    in order that each pointer cell of this array will point to some place
    we need to give it an address some thing like &chr

    "Monday morning" is not an address and its not a single char

    this misunderstanding is for every value in this array

    and we have 4 cells and in char arrays the last cell has to be \0
    so there only place for 3 values

    the 4th cell is www.iota-six.co.uk instaed of \0

    but its wrong

    every char array must end with \0
    and here we changed \0 to www.iota-six.co.uk

    this is wrong

    Code (Text):

    char *strings[4] = { "Monday morning" , "6AM" ,"Sunrise" , "www.iota-six.co.uk"};
  2. jcsd
  3. Oct 20, 2008 #2

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    What you declared is a valid (but better as a const char * array), useful construct that is used quite often.

    You explanation is not what is happening. To begin, char *strings[4] declares an array of 4 "pointers to char", not an indeterminately sized array of character cells of 4 characters each. Big difference. The latter is char strings[][4];.

    You don't want a single character with the above declaration. What you want is a set of things that are can be interpreted as a pointer to a character -- and that is exactly what "Monday morning" is.

    It looks like you might be taking too big a bite of the C language. You first should understand why this works:
    Code (Text):

       const char * string = "Monday morning";
       printf ("As of my post time, it is ridiculously early on %s\n", string);
       string = "Monday afternoon";
       printf ("But if I am lucky I might be able to sneak in a nap on %s", string);
  4. Oct 20, 2008 #3


    User Avatar

    Code (Text):

    char *strings[4] = { "Monday morning" , "6AM" ,"Sunrise" , "www.iota-six.co.uk"};
    What you get is Four pointers. Your declaration is like below:

    char * strings[0]= "Monday morning";
    char * strings[1]= "6AM";
    char * strings[2]= "Sunrise";
    char * strings[3]= "www.iota-six.co.uk"

    NOTE: I write these code above to demonstrate a "pointer array" definition. You can't compile it in the real code. Each pointer has point to a char array with a '\0' added at the end implicitly by the compiler.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook