-2

I want to do something like that:

I am calling a function :

myfunc( .....,  float ** const ouPointer)
{

 ....

float * myPointer;
size_t *AnArray;
    ...
if ( NULL == *ouPointer )
{
        myPointer = (float *) malloc( N * sizeof( float ) );
        assert( NULL != myPointer );
        *ouPointer = myPointer;
}
else
{
        myPointer = *ouPointer;
}

for ( int i = 0; i < N; i++ )
{
    (&myPointer)[ i ] = (float *) malloc( AnArray[ i ] * sizeof( float ) );
    assert( NULL != (&myPointer)[ i ] );
}

//filling pointer

} //end of myfunc 

But it gives me seg fault in assert line.

In order to pass the data to rh function I am using:

float * thePointer = NULL; 
myfunc(...., &thePointer);
George
  • 5,808
  • 15
  • 83
  • 160
  • 2
    Please [do not cast](http://stackoverflow.com/q/605845/2173917) the return value of `malloc()`. – Sourav Ghosh Nov 26 '14 at 13:00
  • 1
    What do you want to do with this line `(&myPointer)[ i ] = (float *) malloc( AnArray[ i ] * sizeof( float ) );`? – mch Nov 26 '14 at 13:01
  • 2
    and please, use a debugger, on linux, `gdb`. – Sourav Ghosh Nov 26 '14 at 13:01
  • @Sourav Ghosh:I am casting because I am using this piece of code also in C++.Also , I am using eclipse debugger and I had only this information – George Nov 26 '14 at 15:35
  • @mch:I want to dynamically allocate space for each myPointer values because they may have different size. – George Nov 26 '14 at 15:36

1 Answers1

1

You are trying to allocate many pointers. And you are trying to have one pointer to store all these pointers. And you are trying to have one pointer to a local variable of the caller, where the caller gets the pointer to the array of pointers back.

In the loop, the code must be

myPointer [i] = (float *) malloc (...). 

myPointer must therefore have type float** - it is a pointer to an array of float*. The declaration and assignment must be

float** myPointer;
myPointer = (float **) malloc( N * sizeof( float* ) );

And finally the parameter must be

myfunc( .....,  float *** const ouPointer)
gnasher729
  • 51,477
  • 5
  • 75
  • 98