c - 循环中动态 malloc - seg 错误

标签 c pointers malloc

我想做这样的事情:

我正在调用一个函数:

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 

但是它在断言行中给了我段错误。

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

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

最佳答案

您正在尝试分配许多指针。并且您正在尝试使用一个指针来存储所有这些指针。并且您试图拥有一个指向调用者的局部变量的指针,调用者在其中获取指向指针数组的指针。

在循环中,代码必须是

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

因此,myPointer 必须具有 float** 类型 - 它是指向 float* 数组的指针。声明和赋值必须是

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

最后参数必须是

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

关于c - 循环中动态 malloc - seg 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27149885/

相关文章:

python - 从分配的数组在 C 中创建一个 numpy 数组会导致内存泄漏

linux - malloc() 是根据单线程还是多线程执行不同的?

c++ - 为二叉搜索树创建一个新节点

arrays - D 编程语言中的指针、函数和数组

c - 为什么用 malloc 初始化的指针是空指针?

c - gcc有可能无法编译代码吗?

c - 将大量节点附加到 xml 树

c - 为什么“while(!feof(file))”总是错误的?

c - 如何编写 scanf 的条件,使其仅接受包含零但不包含字母的整数输入?

哈希表和链接列表的 C++ 访问冲突