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;

}
1
  • 2
    if you wanna pass functions around you should use c++11 features like std::function Commented Jul 25, 2013 at 23:02

1 Answer 1

4

Operator precedence has bitten you. Inside g:

*h[i] is parsed as *(h[i]) but what you want is (*h)[i].

*h[i] is okay for the first iteration, but in the second one (and all subsequent) you're dereferencing an invalid pointer h+i.

On the second thought, you're actually invoking undefined behavior - pointer arithmetic is valid only between pointers that point to the same array.

Sign up to request clarification or add additional context in comments.

2 Comments

You could say you've "shot yourself in the foot". :)
Yes, I am healing my foot right now. But I have another theory question. stackoverflow.com/questions/17889916/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.