A
A
avion2018-12-17 21:31:35
C++ / C#
avion, 2018-12-17 21:31:35

Type conversion and pointer arithmetic?

Hello, please help me understand what is wrong with the code, I do not fully understand what exactly needs to be done.
Task:
Write a function that takes a pointer to double and 2 integers of type int, and writes to the variable pointed to by the pointer-parameter, a number of type double, composed of two integers-parameters ( a number of type double takes 8 bytes; the first integer the number should be from 0 to 3, the second - from 4 to 7).
The code:

#include <iostream>
#include <cstdlib>

using namespace std;

double * func(double *p, int a, int b) {
    double **p1 = &p;
    *(int*)p = a;
    *(int*)p++ = b;
    return *p1;
}

int main() {
    int a = 6, b = 12;
    double s;
    double *p = &s;

    cout << func(p, a, b);

    return 0;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2018-12-17
@jcmvbkbc

double * func(double *p, int a, int b) {
    double **p1 = &p;
    *(int*)p = a;
    *(int*)p++ = b;
    return *p1;
}

Almost correct, except for weird games with p1.
The assignment should probably be like this:
void func(double *p, int a, int b)
{
    *(int*)p = a;
    *((int*)p + 1) = b;
}

To be very strict and avoid language problems (and in the code above, at least type-punning), then this:
void func(double *p, int a, int b)
{
    memcpy(p, &a, 4);
    memcpy((char *)p + 4, b, 4);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question