473,804 Members | 2,959 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

About c++ pointer

/////////////// code 1 start ///////////////////////
char *GetString(void )
{
char p[] = "hello world";
return p;
}
void Test4(void)
{
char *str = NULL;
str = GetString();
cout<< str << endl;
}
/////////////// code 1 end ////////////////////////

///////////////// code 2 start ////////////////////
char *GetString2(voi d)
{
char *p = "hello world";
return p;
}
void Test5(void)
{
char *str = NULL;
str = GetString2();
cout<< str << endl;
}
///////////////// code 2 end /////////////////////

Q: What is the difference between code 1 and code 2?
Jul 22 '05
10 1533
abcd wrote:
Andrey <st*******@yaho o.ca> wrote in message news:<rzgod.296 877$Pl.79890@pd 7tw1no>...
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

Jul 22 '05 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
3058
by: lawrence | last post by:
I've been bad about documentation so far but I'm going to try to be better. I've mostly worked alone so I'm the only one, so far, who's suffered from my bad habits. But I'd like other programmers to have an easier time understanding what I do. Therefore this weekend I'm going to spend 3 days just writing comments. Before I do it, I thought I'd ask other programmers what information they find useful. Below is a typical class I've...
11
25773
by: Dmitry D | last post by:
Hi, I'm new to C++ (started learning in the beginning of this summer), and I have the following question (sorry if it sounds stupid): In many code samples and source files, I see NULL expression being used (for example, int* someInt=NULL; ). I used similar initialization myself, and it works fine even if I don't define NULL. But what is "NULL" exactly? Is it a constant defined by compiler? Is there any difference between the following two...
9
1524
by: wongjoekmeu | last post by:
Hello All, I am learning C++ at the moment. Going through the book of SAM of learning C++ in 21 days I have learned about pointers that it is good custome to always initialise them and to use delete before you try to give it a new address. Can anyone explain to me why this code below which seems to voilate this rule works ? ------------------- int main()
7
2219
by: Rano | last post by:
/* Hello, I've got some troubles with a stupid program... In fact, I just start with the C language and sometime I don't understand how I really have to use malloc. I've readden the FAQ http://www.eskimo.com/~scs/C-faq/faq.html but it doesn't seem to answer my questions... So, I've made an example behind, with some included questions...
7
2492
by: sunglo | last post by:
My doubt comes from trying to understand how thread return values work (I know, it's off topic here), and I'm wondering about the meaning of the "void **" parameter that pthread_join expects (I think this is topical, since it's a C question, but please correct me and apologies if I'm wrong). I suppose that it's this way to allow for "generic" pointer modification, but this implies dereferencing the "void **" pointer to get a "void *"...
7
2198
by: Yuri_Юрий | last post by:
I'm confused about the VARIABLE LENGTH ARRAYS. {scanf("%d",&n);float a;} In which compiler can I use it? I tried VC++6.0 SP6,but it's reported error:CONSTANT EXPRESSION! Another question, What the differences between: (1)ElemType array (2)array=(ElemType*)malloc(N*size of(ElemType)) or array=(ElemType*)calloc(N,size of(ElemType))
14
2418
by: key9 | last post by:
Hi All On coding , I think I need some basic help about how to write member function . I've readed the FAQ, but I am still confuse about it when coding(reference / pointer /instance) , so I think I need some "template". Sorry for my coding experience in c++
68
15720
by: James Dow Allen | last post by:
The gcc compiler treats malloc() specially! I have no particular question, but it might be fun to hear from anyone who knows about gcc's special behavior. Some may find this post interesting; some may find it off-topic or confusing. Disclaimers at end. The code samples are intended to be nearly minimal demonstrations. They are *not* related to any actual application code.
4
1747
by: Deep | last post by:
I'm in doubt about what is smart pointer. so, please give me simple description about smart pointer and an example of that. I'm just novice in c++. regards, John.
17
2398
by: DiAvOl | last post by:
Hello everyone, merry christmas! I have some questions about the following program: arrtest.c ------------ #include <stdio.h> int main(int agc, char *argv) {
0
9704
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9571
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10318
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10302
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10069
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5639
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4277
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3803
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2976
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.