Home > OS >  cast from 'char*' to 'int' loses precision
cast from 'char*' to 'int' loses precision

Time:12-31

am having a problem converting a char* into am int in a 64 bit machine . i know the problem is on 64 bit sizeof(char*) is 8 and sizeof(int) is 4. here's the code :

void books::update()
{
    int b_id[100],qty[100],i=0,max;
    stmt.str("");
    stmt<<" Select book_id,qty from purchase where recieves ='T' and inv IS NULL;";
    query=stmt.str();
    q =query.c_str();
    mysql_query(conn,q);
    res_set=mysql_store_result(conn);
    stmt.str("");
    stmt<<" Update purchases set inv=1 where recieves ='T' and inv is NULL";
    query=stmt.str();
    q=query.c_str();
    mysql_query(conn,q);
    while((row=mysql_fetch_row(res_set))!=NULL)
    {
        b_id[i]=(int)row[0];
        qty[i]= (int)row[1];
        i  ;
    }
    max=i;
    for(i =0;i<max;i  )
    {
        stmt.str("");
        stmt<<" update books set qty ="<< qty[i]<<"where id = "<<b_id[i]<<";";
        query= stmt.str();
        q= query.c_str();
        mysql_query(conn,q);


    }
    cout<<" The order recieved has been updated .";



}

the bug is in these two lines :

b_id[i]=(int)row[0];
qty[i]= (int)row[1];

i tried to use (long) instead of (int) ,expecting it to convert my int from 4 bytes to 8 bytes and i still got the same error (cast from 'char*' to 'int' loses precision )

CodePudding user response:

Change int to std::intptr_t everywhere, including the array declarations. You need #include <cstdint> for that.

More info about integer types in C : https://en.cppreference.com/w/cpp/types/integer

CodePudding user response:

The standard library has two fixed width typedefs capable of holding a pointer to void which are defined in <cstdint>:

std::intptr_t   // signed
std::uintptr_t  // unsigned

However, you do not convert a C string to an integer via a cast. The C string must be interpreted somehow. Example:

#include <sstream>

// ...

// put the two C strings in an istringstream:
std::istringstream is(std::string(row[0])   ' '   std::string(row[1]));

// and extract the values
if(is >> b_id[i] >> qty[i]) {
    // success
}

Other options are to use std::stoi or std::strtol. Example:

b_id[i] = std::stoi(row[0]); // may throw std::invalid_argument ...
qty[i] = std::stoi(row[1]);  // ... or std::out_of_range 

CodePudding user response:

You need a long long, not a long to perform the cast. But I doubt that this will solve your problem at all.

  •  Tags:  
  • c
  • Related