简体   繁体   English

C ++将对数组的引用传递给C函数

[英]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. 我试图调用用C编写的函数,该函数将指针传递给数组。

In C++ I have the following: 在C ++中,我具有以下内容:

double* x = new double[10];

populateArray(x);

In C: 在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? 但是,当我尝试在C ++代码中输出x的内容时,结果始终为0?

Problem arises because you are changing local variable vars . 出现问题是因为您正在更改局部变量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. 问题是您忽略了给定的vars ,并为其创建了一个全新的缓冲区。

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. 只需使用您获得的vars请删除上面指示的行。

Short answer: Remove the malloc call inside the function. 简短答案:删除函数内部的malloc调用。

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). 您正在将vals指针的值更改为另一个新分配的内存-因此,您传入的参数将变为未使用的(因此永远不会填充)。

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. 结果始终为0是一个巧合,它可以是任何东西(或者您可能会患上鼻恶魔 ),因为您随后将读取未初始化的内存,这是未定义的行为。

This of it as this, if you remove the call: 如果您删除呼叫,则如下所示:

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

The first value is overwritten. 第一个值将被覆盖。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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