Memory access by address



  • hey bros;
    I have a program to access the variables by their addresses and this is my code:

    float f;
    int t;

    QHash <int,int*> hash;
    hash.insert(1,&t);
    hash.insert(2,(int*)&f);

    *hash.value(1)=34;
    qDebug()<<"t1="<<t1; //t1= 34

    *hash.value(2)=456.987;
    qDebug()<<"f="<<f; //f=7.94536e-43 !!!!!!

    why this code is not working? and how can i fix that?
    Actually the objective of this code is to indexing every variable with any type (int, float, structure, Boolean, .. ) by an integer number. Hashing is used to achieve this goal.
    Thanks a lot



  • If i use QVariant like below:

    @QHash <int,QVariant*> hash;
    @
    and i insert the same values into it, i encounter this error:

    : error: C2664: 'QHash<Key,T>::insert' : cannot convert parameter 2 from 'int *' to 'QVariant *const &'
    with
    [
    Key=int,
    T=QVariant *
    ]

    But if i use the previous code and retrieve the address as below:
    @(float)hash.value(2)=456.987;
    qDebug()<<“f=”<<f; //f=456.987@

    everything will be OK.



  • Hi,
    Better to not use pointers to your variables for this. A QVariant will use the same amount of memory space as the variable it will point to. So, the QHash should have an <int, QVariant> not the pointer. Then add the variable to the QVariant via a constructor or other variant function and you should be able to convert any variable into that QHash. Even mix them if needed.



  • hey Jeroentje@home
    thanks for your reply But could you please make an example of your plan?


  • Lifetime Qt Champion

    Jeroentje@home meant that you should follow koahnig's example

    @
    QHash<int, QVariant> hash;
    float fInput= 1.2
    hash.insert(1, fInput);
    float myFloat = hash.value(1).toFloat();
    @


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.