473,763 Members | 5,396 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Returning a pointer to a struct

Hey all,

I want to return a pointer to a struct. Here is what I'lm trying to do:

struct Position{
int x;
int y;
};

Position* GraphicTag::get RenderCentre(){
int cenx = m_renderPositio n->x + m_size->width / 2;
int ceny = m_renderPositio n->y + m_size->height / 2;

return (Position *){cenx,ceny}; // <---- Error here
}

I get "Error: initializer for scalar variable requires one element".
I'm a Java programmer at heart, and still a little uneasy around
pointers.

Thanks,
Matt

Nov 30 '06 #1
17 3238

dj*****@gmail.c om schrieb:
I want to return a pointer to a struct. Here is what I'lm trying to do:

struct Position{
int x;
int y;
};

Position* GraphicTag::get RenderCentre(){
int cenx = m_renderPositio n->x + m_size->width / 2;
int ceny = m_renderPositio n->y + m_size->height / 2;

return (Position *){cenx,ceny}; // <---- Error here
}

I get "Error: initializer for scalar variable requires one element".
I'm a Java programmer at heart, and still a little uneasy around
pointers.
With a simple data structure like this, it does not make much sense to
use pointers at all. In C++, I would personally try to return a simple
structure like this by value or by reference first, and only as a last
resort would I use pointers.

You get the error since a pointer in C++ needs (or should) point to
something. In other words, you need to create a valid object to point
to first.

Your structure also has no applicable default constructor that could
help you here. You should consider adding one.

And finally, if you have this function create a "Position" object and
return a pointer to it, the caller will be responsible for deleting the
object - not necessarily a desired behaiour.

Alf P. Steinbach (frequent contributor in this group) has a good
tutorial on C++ pointers:
http://home.no.net/dubjai/win32cpptu...ters/ch_01.pdf

Cheers,
Andre

Nov 30 '06 #2
dj*****@gmail.c om wrote:
I want to return a pointer to a struct. Here is what I'lm trying to
do:

struct Position{
int x;
int y;
};

Position* GraphicTag::get RenderCentre(){
int cenx = m_renderPositio n->x + m_size->width / 2;
int ceny = m_renderPositio n->y + m_size->height / 2;

return (Position *){cenx,ceny}; // <---- Error here
}

I get "Error: initializer for scalar variable requires one element".
I'm a Java programmer at heart, and still a little uneasy around
pointers.
Pointers are good when you have objects addresses of which you can
take and assign to those pointers. Your "{cenx,ceny }" syntax is not
C++. If you want to move along in C++, you'll need to un-learn some
of Java.

In this particular case do NOT return a pointer. Return an object:

Position GraphicTag::get RenderCentre(){
Position retval = { m_renderPositio n->x + m_size->width/2,
m_renderPositio n->x + m_size->height/2 };
return retval;
}

Of course, it's better to make your Position to have a c-tor that
would take two values and construct a temporary right in the
return expression.

struct Position{
int x;
int y;
Position(int xx, int yy) : x(xx), y(yy) {}
};

...
return Position( m_renderPositio n..../2, m_render.../2 );
}

There are implications about adding your own c-tor to the struct,
so you decide which path to take.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Nov 30 '06 #3
Thank you both,

Firstly, what is the scope of a struct which is created (not as a
pointer) in a member function? I always thought it was local only
(would delete when the function is returned), but I'm clearly wrong
here. Does it last until the object that the member function belongs to
is destroyed?

Secondly, am I correct in thinking that there is no "inline" way of
creating a pointer to a struct like I was trying to, unless I define a
constructor? (I'm very stubborn, even if it isn't the right way, I like
to know where I was going wrong with the syntax).

Thanks again,
Matt

Nov 30 '06 #4

dj*****@gmail.c om wrote:
Thank you both,

Firstly, what is the scope of a struct which is created (not as a
pointer) in a member function? I always thought it was local only
(would delete when the function is returned), but I'm clearly wrong
here. Does it last until the object that the member function belongs to
is destroyed?
The object created within the function has the scope of that function
and is indeed destroyed[*] at the end of that function. However, when
you return by value as Victor suggested, a whole new, entirely separate
object is created for the return value. So by the end of the function,
the local object has been destroyed, but that doesn't matter because
the return value is a different object that was created as a copy of
the local object while the local object still existed.
[*] Destroyed, not deleted. delete in C++ has a very specific meaning
(as a keyword, in all lower case). It is what you do to objects with
dynamic storage duration (those created with new) when you, the
programmer, decide it is time for them to cease existing.

Gavin Deane

Nov 30 '06 #5
dj*****@gmail.c om wrote:
[..]
Secondly, am I correct in thinking that there is no "inline" way of
creating a pointer to a struct like I was trying to, unless I define a
constructor?
You can use syntax Position() for a default-initialised temporary, if
it can, the compiler declares and defines the default constructor for
you. In your case it doesn't make sense, of course.
(I'm very stubborn, even if it isn't the right way, I
like to know where I was going wrong with the syntax).
Well, the curly-brace enclosed initialiser list syntax is only used
(and available) in _declarations_, not in expressions. The 'return'
statement includes an expression. You can, as you know _declare_
(and define) your struct as

Position blah = { 1, 2 };

Here the "{ 1, 2 }" is the allowed initialiser syntax. You cannot
do, for example

foo( { 1, 2} );

(for some function 'foo' that takes 'Position' as its argument). It
is not allowed. If you need to create a temporary object and give it
some non-default value[s], the class has to define a c-tor, so you
can use the syntax

foo( Position(1,2) );

, for example.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Dec 1 '06 #6

dj*****@gmail.c om wrote:
Thank you both,

Firstly, what is the scope of a struct which is created (not as a
pointer) in a member function? I always thought it was local only
(would delete when the function is returned), but I'm clearly wrong
here. Does it last until the object that the member function belongs to
is destroyed?
A struct doesn't have a scope - it doesn't exist. An instance of a
struct does.
The local variable dies with the function but if you return the
variable, a copy ctor creates a brand new object in main for you.
>
Secondly, am I correct in thinking that there is no "inline" way of
creating a pointer to a struct like I was trying to, unless I define a
constructor? (I'm very stubborn, even if it isn't the right way, I like
to know where I was going wrong with the syntax).

Thanks again,
Matt
Look at it this way. If you *could* use a pointer, you'ld be much
better off using a const reference instead. Pointers are responsible
for most of the bugs that programs suffer from. Even in the case of
allocations, pointers should be replaced by smart_ptr(s) and references
work nicely with polymorphism.
A C++ programmer'ss ultimate goal is (or should be) to write an entire
application without ever directly using a pointer. The resulting code
will be safer, bug-proof, easily maintainable and effortlessly
expandable/extendable.

The solution: a const reference. The only viable alternative is return
by copy. Are you ready? Cause there is a moral to the story...

#include <iostream>

class Position {
int x, y;
public:
Position() : x(0), y(0)
{
std::cout << "Position() \n";
}
Position(int x_, int y_) : x(x_), y(y_)
{
std::cout << "Position(i nt, int)\n";
}
Position(const Position& copy)
{
std::cout << "copy Position\n";
x = copy.x;
y = copy.y;
}
int getx() const { return x; }
int gety() const { return y; }
};

class Graphic
{
Position pos; // precious coordinate
public:
Graphic() : pos() { }
void move(const Position& r_pos)
{
pos = r_pos;
}
const Position& getpos() const // by const ref
{
return pos;
}
};

int main()
{
Graphic graphic;
graphic.move( Position(10,10) );
Position gpos = graphic.getpos( );
std::cout << "pos.x = " << gpos.getx();
std::cout << "\npos.y = " << gpos.gety();
std::cout << std::endl;
}

/*
Position() // 0,0
Position(int, int) // 10,10
copy Position // the reference is copied safely
pos.x = 10
pos.y = 10
*/

Graphic's getpos() above is a viable candidate for a pointer return
since its returning an internal member. Thing is: why would i want a
user of the class to have *access* to my precious graphic's Position?
Even if it were to be accessed + modified by accident? You could return
a constant pointer - but then some smart-ass can const_cast<your
precious position into oblivion. I'm not joking - i'm dead serious.

Consider:

Position* const Graphic::getpos () // by constant pointer
{
return &pos;
}

some smart ass could write the following side-effect:

*graphic.getpos () = Position(-1,-1); // modifies your private member
!!!

and screw you royally. Try it. Even if getpos() is made const, i can
*still* modify the internal position with a Postion ptr and a
const_cast<>.

Forget doing that with a const reference. Its absolutely nuke-proof.

Dec 1 '06 #7
Salt_Peter <pj*****@yahoo. comwrote:
>A struct doesn't have a scope - it doesn't exist.
Sure it does. Try compiling the following.

void foo () {
{
struct goo {
int a;
};
goo b; // legal
}
goo c; // illegal, causes 'goo undeclared'
}

Steve
Dec 1 '06 #8

Steve Pope wrote:
Salt_Peter <pj*****@yahoo. comwrote:
A struct doesn't have a scope - it doesn't exist.

Sure it does. Try compiling the following.

void foo () {
{
struct goo {
int a;
};
goo b; // legal
dandy, but hardly the context at hand.
And lets not get confused with an instance's scope, type visibilty and
type accessibility.
What you have above is a struct in a closed anonymous namespace.

namespace GOO {
struct goo { };
}

void foo () {
GOO::goo b;
}

GOO::goo c;

int main()
{
GOO::goo d;
}

Dec 1 '06 #9
Salt_Peter <pj*****@yahoo. comwrote:
>Steve Pope wrote:
>Salt_Peter <pj*****@yahoo. comwrote:
>>A struct doesn't have a scope - it doesn't exist.
An instance of a struct does.
>Sure it does. Try compiling the following.
>void foo () {
{
struct goo {
int a;
};
goo b; // legal
>dandy, but hardly the context at hand.
And lets not get confused with an instance's scope, type visibilty and
type accessibility.
You're right that my point does not address the OP's concern, however
your statement above seemed to imply that you believe a structure
declaration (as opposed to the definition of an instance of the
structure) doesn't have scope. It does, and can be (among perhaps
other possibilities) either global to a file or local to a block.
>What you have above is a struct in a closed anonymous namespace.

namespace GOO {
struct goo { };
}

void foo () {
GOO::goo b;
}

GOO::goo c;

int main()
{
GOO::goo d;
}
I'm not sure I totally agree that names local to a block are
identical in behavior to names in an anonymous namespace. For one
thing, a name can be declared in an anonymous namespace and then used
outside the namespace's block but within the same file.

They are somewhat different scoping mechanisms.

Steve
Dec 1 '06 #10

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

Similar topics

11
2067
by: kelvSYC | last post by:
What is the best way to create functions that, based on some input, return either structures or a null value if the structure cannot be made? The problem is that the structure has be created inside the function, and I've heard that returning a pointer to a locally created structure is unsafe. -- I am only a mirage.
4
4987
by: Anthony | last post by:
Hello, I am writing a function that populates an array of pointers to strings. Both the number of strings in the array, and the lengths of the strings, are dynamic; in particular, the number of strings won't be known until just before the function returns. The problem is that in the calling function, I need to know both the address of the array, and the number of strings. My first thought was to pass a pointer to the array into the...
6
2428
by: Generic Usenet Account | last post by:
Is it okay to return a local datastructure (something of type struct) from a function, as long as it does not have any pointer fields? I think it is a bad idea, but one of my colleagues does not seem to think so. According to my colleague, if the data structure does not "deep copy" issues, it is perfectly okay to return a local variable. This is because at the point of invocation, a copy of the data structure is made. In all fairness...
3
2847
by: Michel Rouzic | last post by:
It's the first time I try using structs, and I'm getting confused with it and can't make it work properly I firstly define the structure by this : typedef struct { char *l1; int *l2; int Nval; } *arrays; It's supposed to be a structure containing an array of chars, an array of ints and an int. I declare functions like this : arrays *parseline(char *line, int N)
17
3260
by: I.M. !Knuth | last post by:
Hi. I'm more-or-less a C newbie. I thought I had pointers under control until I started goofing around with this: ================================================================================ /* A function that returns a pointer-of-arrays to the calling function. */ #include <stdio.h> int *pfunc(void);
6
1787
by: student1976 | last post by:
All Beginner/Intermediate level question. I understand that returning ptr to local stack vars is bad. Is returning foo_p_B from fnB() reliable all the time, so that using foo_p_A does not break? Thanks Josh
3
3663
by: John Turner | last post by:
typedef void (*vfp)(); typedef vfp (*fp)(); static fp hello() { printf("Hello.\n"); return (fp)&hello; } main(){
17
1693
by: daniel | last post by:
Hello , How safe is it to return a structure from a function. Let's say we have the following situation: typedef struct MyStruct{ int a;
5
2680
by: ctj951 | last post by:
I have a very specific question about a language issue that I was hoping to get an answer to. If you allocate a structure that contains an array as a local variable inside a function and return that structure, is this valid? As shown in the code below I am allocating the structure in the function and then returning the structure. I know if the structure contained only simple types (int, float) this will work without problems as you...
0
10148
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10002
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...
0
8822
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7368
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6643
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5406
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3917
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
3528
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2794
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.