Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Re: Difference between Char* ptr and char arrCh []

2 views
Skip to first unread message

Nick Keighley

unread,
Jul 28, 2009, 4:52:41 AM7/28/09
to
X-posted to comp.lang.c++

On 27 July, 17:55, AY <techreposit...@gmail.com> wrote:

> I have a few queries regarding array of characters using array
> notation and pointer notation.
>
> [ #1 ]
>
> Is there a difference in storage of global char* and char* inside a
> function ?
>
>  consider the code:
>
>           char* globalCh = "MY STRING";
>
>          void foo()
>          {
>                char* simpleCh = "My String";
>          }
>
> What I understand is in the case of  'char* simpleCh' - the
> pointer .i.e. ' *simpleCh' is stored in the stack, while the value "
> My String" is stored elsewhere in a data segment.  Taking the sizeof
> (simpleCh) would be 4 bytes in my machine. Once the function exits "My
> String" is no longer accessible.
>
> Taking the sizeof(globalCh) = 4 bytes and where is the value ' MY
> STRING ' and the pointer  ' *globalCh ' stored ? since its a global
> variable the storage of the pointer  ' *globalCh ' should be in a
> static area. That means should it be in the code segment?
>
> [ #2 ]
>
>      void foo()
>      {
>          char* pch = new char[25];

this isn't valid C (C has no new operator). If you are coding
in C++ why not use std::vector or even std::string. This avoids
the problems you are having with assigning strings etc.

I usually find using the array form of new is a mistake
(at least it's an easy way to grep a source base for potential
mistakes!)

>          strncpy(pch, "ABCD", 4);
>          pch[4] = '\0';
>
>          // pch = "KLMN"; // ERROR !
>      }
>
> We can't de-reference pch = "KLMN"; Is it because 'pch' allocated in
> the heap, while "KLMN" is in some variable location?
>
> [ #3 ]
>
> Assuming
>               char* str = "ABCD"; is same as  const char* str =
> "ABCD"; [ what it points to is constant ], but we can dereference as
>
>           str = "XYZ"; // OK !
>           str[1] = 'L';  // ERROR !!!!
>
> Can we think of char arrCh[] = " ABCD" as ' char * const arrCh
> ' ( i.e. we can't modify the address ) ?
>
> We can't dereference
>
>      arrCh = "XYZ"; // ERROR !
>      arrCh[ 2 ] = 'K' ; // Fine !
>
> [ #4 ]
>
> Which one of the ' char array ' notation is the most preferred one, is
> it the pointer notation ( char *ptr = " ABCD" )  or the array notation
> ( char arrCh[] = "ABCD" ) ? Why is it one preferred over the other?
>
> Appreciate your suggestions,

pick a language

--
Nick Keighley

"I wish to God these calculations had been accomplished by steam."
--C. Babbage

0 new messages