Re: About c++ pointer
From: Cheng Mo (mo.cheng_at_nospam.nospam)
Date: 11/24/04
- Next message: jjr2004a: "Re: Accessing inherited operator<< in base class from derived class"
- Previous message: Evan Carew: "Re: c++ on linux"
- In reply to: abcd: "Re: About c++ pointer"
- Next in thread: Peter Koch Larsen: "Re: About c++ pointer"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Wed, 24 Nov 2004 10:51:38 +0800 To: abcd <abcd_68@yahoo.co.uk>
abcd wrote:
> Andrey <stingo000@yahoo.ca> wrote in message news:<rzgod.296877$Pl.79890@pd7tw1no>...
>
>>zhou xiang wrote:
>>[...]
>>
>>>Q: What is the difference between code 1 and code 2?
>>
>>The code 1 will not work, the pointer will be empty when it returns,
>>because the object(string array) is created in stack. While the second
>>is fine since you dynamically allocate memory in the heap.
>
>
> Nope. In neither case is the memory allocated off the heap (I can't
> see any 'new' or 'malloc'). In both cases the string is statically
> allocated in read-only memory (try to change it and the program will
> likely crash e.g., *p='f').
>
> The difference between the two is that in the first listing p is an
> actual array, allocated on the stack. The contents of the constant
> string is copied into it. It will be destroyed as soon as the flow of
Perhaps your words is a little misleading.
The statement "char p[] = "hello world";" equals "char p[] =
{'h','e','l','l','o',' ','w','o','r','l','d','\0'};"
It is just a initializtion of a char array. No "copy" is performed.
> control leaves function GetString(). This means that you're returning
> the address of a local (and a clever compiler issues a warning). The
> second listing is fine, not because you're allocating memory off the
> heap (which you're not) but because you're returning a pointer to a
> statically allocated string which will be there as long as the program
> runs.
>
> HTH
> Andy
- Next message: jjr2004a: "Re: Accessing inherited operator<< in base class from derived class"
- Previous message: Evan Carew: "Re: c++ on linux"
- In reply to: abcd: "Re: About c++ pointer"
- Next in thread: Peter Koch Larsen: "Re: About c++ pointer"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|