c - 在函数内部分配内存并将其返回

标签 c memory pointers allocation malloc

我想传递一个指针给我的函数,并分配这个指针指向的内存。我在其他帖子中读到我应该将双指针传递给这个函数并且我这样做了,但是我一直遇到段错误:

#include <iostream>
#include <stdlib.h>

using namespace std;

void allocate(unsigned char** t)
{
    *t=(unsigned char*)malloc(3*sizeof(unsigned char));
    if(*t == NULL)
        cout<<"Allcoation failed"<<endl;
    else
        for(int m=0;m<3;m++)
            *(t[m])=0;
}

int main()
{
    unsigned char* t;
    allocate(&t); 
    cout<<t[0]<<" "<<t[1]<<endl;
    return 0;
}

结果总是这样: 段错误(核心转储)

我认为这段代码没有遗漏任何内容。有什么问题吗?

最佳答案

看看这一行:*(t[m]) = 0;。由于您已赋予 t[m] 优先级,因此它将寻找指向 char 的第 m 指针并取消引用它。你真正想要做的是取消引用 t 并找到 char m 之后的地方,或者 (*t)[m] 。进行此更改会使您的代码完美运行:http://ideone.com/JAWeS2

关于c - 在函数内部分配内存并将其返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25389578/

相关文章:

C程序遇到EOF或-1不会停止

c - 在优化中迷失/困惑

c - 如何从 ISO 将内核加载到内存中

c++ - 执行被信号 11 终止(可以通过违反内存限制触发)

c - 错误: Void value not ignored as it ought to be in C programming

将整数值转换为 ip 地址

string - 在 Rust 中 .clear() 然后 .push_str(String) 安全吗?

c++ - 为什么 valgrind 在内存泄漏检测期间被杀死?

c - 将 3D 数组的 3 个基本 block 地址的基地址存储到数组指针中?

c++ - 来自用作模板参数的指针的类类型