2

I get a segmentation fault when reading the second element of h array inside the g function. Strangely, when debugging can I actually watch the array content. I think that besides this curious thing that shows that the data is there, I have done something wrong. Thanks in advance.

#include <iostream>

using namespace std;

void function(void function_passed(double* [], int), int n);

void g(double* [] ,int n_g);

int main()
{
    function(g,5);

    return 0;
}

void g(double* h[], int n_g)
{
    for (int i = 0; i < n_g; i++)
        cout << i << " "<< *h[i] << endl;
}

void function(void function_passed(double* [], int ), int n)
{
    double * h = new double[n];

    for (int i=0;i<n;i++)
        h[i] = i + 10;

    function_passed(&h,n);

    delete[] h;

}



void func(void g(double* [],int n ), int n)
{
    double * h = new double[n];

    for (int i=0;i<n;i++)
        h[i] = i;

    g(&h,n);

    delete[] h;

}
4

1 回答 1

4

运算符优先级已经咬了你。内部g

*h[i]被解析为*(h[i])但你想要的是(*h)[i].

*h[i]第一次迭代没问题,但在第二次(以及所有后续)中,您取消引用了一个无效的指针h+i

再想一想,您实际上是在调用未定义的行为-指针算术仅在指向同一数组的指针之间有效。

于 2013-07-25T23:04:21.573 回答