Is there any difference between returning a pointer to a struct, and returning a struct? Aside from the derefrenceing that is done would they both be working with the same struct? Is there any copying that gets done if it is just a regular return?
overwraith
83
Newbie Poster
Recommended Answers
Jump to PostWhen you have a function in C (or C++), the function gets an area of memory on the stack to use for its local variables. If you create a variable like this:
MyStruct X;
inside your function, then the X structure will get created on the stack. If you return …
Jump to PostCorrect, except for the part about the pointer. When you allocate something on the heap, the heap stays around and is there for all the functions to share. (In C, I think you use "malloc" to allocate it on the heap. I haven't done straight C in years though.) So …
Jump to PostNo, when it's on the heap it stays right there and the main and other functions just access it through the pointer. The pointer gets passed around and anyone can use it.
Jump to PostOh! Sorry, I guess I didn't explain that. When you call malloc in C or new in C++, it gets created on the heap and you get a pointer to its location in the heap.
Jump to PostSo you don't actually have to copy it into the heap. It gets created there.
All 17 Replies
jeffcogswell
175
Light Poster
Featured Poster
overwraith
83
Newbie Poster
jeffcogswell
175
Light Poster
Featured Poster
overwraith
83
Newbie Poster
jeffcogswell
175
Light Poster
Featured Poster
overwraith
83
Newbie Poster
jeffcogswell
175
Light Poster
Featured Poster
jeffcogswell
175
Light Poster
Featured Poster
overwraith
83
Newbie Poster
Moschops
683
Practically a Master Poster
Featured Poster
overwraith
83
Newbie Poster
Moschops
683
Practically a Master Poster
Featured Poster
cambalinho
125
Practically a Posting Shark
overwraith
83
Newbie Poster
Moschops
683
Practically a Master Poster
Featured Poster
jeffcogswell
175
Light Poster
Featured Poster
overwraith
83
Newbie Poster
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.