C++ size_t and double type calculation

1.5k views Asked by At

I am not familiar with C++ and current face a problem about size_t calculation with double type. I provide a part of source code as below. The variable "storage" is define as double and "pos" as size_t type. How come they can be calculate together? I review the value of "pos and it shows value like 0, 1, 2 and so on. Moreover, in the case of double* result = storage + pos, it shows 108 + 2 comes out the result x 117.

Further, sometimes 108 + 0 comes out the result x zero. what the condition lead to the result?

How do I know the exact value of size_t before the calculation?

Any advice & suggestion is appreciated.

    double* getPosValue(size_t pos, IdentifierType *idRule, unsigned int *errorNumber, bool *found)
{

    double * storage = *from other function with value 108*

    double* result = storage + pos;
    uint16_t* stat = status + pos;   }
1

There are 1 answers

5
paxdiablo On BEST ANSWER

The size of a variable (or type) can be obtained with:

sizeof(variableNameOrTypeName)

If you're after the address of a given array element such as variableName[42], it's simply:

&(variableName[42])

with no explicit mucking about with pointers.

If you want to manipulate the actual double value when you only have a pointer to it, you need to dereference the pointer. For example:

double xyzzy = 108.0;     // this is the VALUE.
double *pXyzzy = &xyzzy;  // this is a POINTER to it.

double plugh = *pXyzzy + 12.0;

The final line above gets the value from the pointer (*pXyzzy) and adds twelve to that, before storing it into another variable named plugh.


You should be very wary of things like:

double * storage = 108;

That creates a pointer to a double with the address of 108. In no way does it create an actual double with the value 108. Dereferencing that pointer is likely to lead to, shall we say, interesting results :-)