简体   繁体   中英

C++ passing reference to array to C function

I'm trying to call a function written in C which passes in a pointer to an array.

In C++ I have the following:

double* x = new double[10];

populateArray(x);

In C:

void populateArray(double* vars); 
{
    vars = (double*) malloc(10*sizeof(double));

    int i;

    for(i = 0; (i < 10); i++)
    {
        vars[i] = 1*20;
    }
}

However, when I try to output the contents of x inside the C++ code, the result is always 0?

Problem arises because you are changing local variable vars .

Change to:

double* x; //you don't need to allocate here if you are allocating later

populateArray(&x);

And:

void populateArray(double** vars) 
{
    *vars = malloc(10*sizeof(double)); //also no need to cast malloc

    int i;

    for(i = 0; (i < 10); i++)
    {
        (*vars)[i] = 1*20;
    }
}
void populateArray(double* vars); 
{
    vars = (double*) malloc(10*sizeof(double)); // <---- remove this line completely

The problem is you're ignoring the vars you were given and creating a brand new buffer for it.

Worse, that buffer pointer gets lost when this function returns, causing a memory leak.

Just use the vars you were given -- delete the line indicated above.

Short answer: Remove the malloc call inside the function.

Slightly longer answer:

You're changing the value of the vals pointer to another newly allocated memory -- thus, the argument you pass in gets unused (and thus is never populated).

The result being always 0 is a coincidence, it could be anything (or you could end up with nasal demons ) because you're then reading uninitialized memory, which is undefined behavior.

This of it as this, if you remove the call:

vals = new double[10];
vals = malloc(10 * sizeof(double));

The first value is overwritten.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM