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;

}
Pablo Riera
  • 349
  • 3
  • 15

1 Answers1

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.

jrok
  • 54,456
  • 9
  • 109
  • 141
  • You could say you've "shot yourself in the foot". :) – jrok Jul 25 '13 at 23:09
  • Yes, I am healing my foot right now. But I have another theory question. http://stackoverflow.com/questions/17889916/c-is-the-same-passing-an-array-than-a-pointer-to-array – Pablo Riera Jul 26 '13 at 19:55