malloc动态地循环 - seg错误

时间:2022-10-11 20:00:09

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.

但它在断言行中给出了seg错误。

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

为了将数据传递给rh函数我正在使用:

float * thePointer = NULL; 
myfunc(...., &thePointer);

1 个解决方案

#1


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

因此myPointer必须具有float **类型 - 它是一个指向float *数组的指针。声明和作业必须是

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

And finally the parameter must be

最后参数必须是

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

#1


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

因此myPointer必须具有float **类型 - 它是一个指向float *数组的指针。声明和作业必须是

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

And finally the parameter must be

最后参数必须是

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