Array of pointers

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Slain

    Array of pointers

    I have more of a conceptual question now. Let us say I do this:-

    char *str[10]; --create an array of pointers
    str[1]= "John";

    I thought this would automatically put John at some memory space and
    point str[1] to it.
    My colleague argues that in flat bed memory this should not be done. A
    new should be used to allocate the memory and then point to it. Of
    course he didnt do the best job explaining, hence my question to you
    guys, if you can shed some more light on this.

    Thanks in anticipation
  • utab

    #2
    Re: Array of pointers

    On Mar 5, 3:29 pm, Slain <Slai...@gmail. comwrote:
    I have more of a conceptual question now. Let us say I do this:-
    >
    char *str[10]; --create an array of pointers
    str[1]= "John";
    >
    I thought this would automatically put John at some memory space and
    point str[1] to it.
    Correct me if I am wrong but str[1] is used to dereference. str[1]
    actually is the character array itself.

    AFAIK, str points to the start address of the array and index notation
    provides offsets to the character arrays which are dereferenced
    through these addresses of the character arrays.

    Hope I did not make big mistakes above.

    Comment

    • Szabolcs Ferenczi

      #3
      Re: Array of pointers

      On Mar 5, 3:29 pm, Slain <Slai...@gmail. comwrote:
      I have more of a conceptual question now. Let us say I do this:-
      >
      char *str[10]; --create an array of pointers
      str[1]= "John";
      >
      I thought this would automatically put John at some memory space and
      point str[1] to it.
      I think your reading is correct and by a quick test the compiler also
      confirms this. You can check it yourself with help of this guide:



      Your declaration reads: "declare str as array 10 of pointer to char"
      Since you said you need an array of 10 pointers, a pointer array of
      size 10 will be allocated too.
      My colleague argues that in flat bed memory this should not be done. A
      new should be used to allocate the memory and then point to it.
      I think it is a programming language question and as such it is
      independent of any physical realization of the storage.

      Your colleague would be right, but not because of any kind of storage
      implementation, if you declared it like this:

      char **str; /* "declare str as pointer to pointer to char" */

      In this case you declare a single pointer, so only what is declared
      will be allocated.

      Best Regards,
      Szabolcs

      Comment

      Working...