MistyD
MistyD

Reputation: 17223

Converting a float to float*

I have QStandardItem* list in my code

QList<QStandardItem*> lst

Now this is acceptable and works

float a = lst[0]->text().toFloat();

However the following does not work

float* a = &(lst[0]->text().toFloat());

I get an intellisense error stating

Expression must be an lvalue or a function designator

I need a pointer here since I am using an external library that requires a reference that looks like this

 some_class.add_variable(const std::string& variable_name, float& t);

So if I get a pointer I could simply pass it as *a

Any suggetsions on how I could resolve this issue ?

Upvotes: 1

Views: 148

Answers (5)

Bathsheba
Bathsheba

Reputation: 234635

Take care: float* a = &(lst[0]->text().toFloat()); will give you undefined behaviour if you refer to a following this statement. This is because the anonymous temporary (the float returned by .tofloat()) will be out of scope after the statement and a will be invalidated; i.e. will not point to anything meaningful.

You should write float a = lst[0]->text().toFloat(), and pass &a to the function. That is, keep a in scope for as long as you need it.

Upvotes: 0

Mats Petersson
Mats Petersson

Reputation: 129314

Actually, your external function does NOT need an address, it takes a REFERENCE, so you don't need a pointer.

However, if you really need the pointer to a local variable:

float x = something...;
some_function(&x);

will give you what you are after.

Upvotes: 0

tadman
tadman

Reputation: 211540

Taking the address of a temporary value returned by a function is not going to work. This value is supposed to be assigned to an lvalue variable.

Why do you want the address of the float instead of the actual value?

You should only be dealing with addresses of, or pointers to values that have been saved somewhere.

Upvotes: 0

Chris Hayes
Chris Hayes

Reputation: 12020

The right hand side is what's called a temporary. It is an object which will not exist after the end of the current expression. For obvious reasons, you can't take the address of temporaries; after the expression ends you'd have an invalid pointer.

What you could do is this:

float a = lst[0]->text().toFloat();
float* aPtr = &a;

That will safely make a copy of the temporary value (or in C++11, it may move the temporary), and you can then take a reference to your local, non-temporary variable.

Upvotes: 3

Jesus Ramos
Jesus Ramos

Reputation: 23268

Use float a = lst[0]->text().toFloat(); and simply pass it as &a to the library function.

Upvotes: 2

Related Questions