c - 如何在函数内初始化和分配 char** 参数

标签 c pointers memory-management arguments

我有一个由 main 调用的 readfile 函数。标准是我必须将 char** 传递到 readfile 中,并且必须在 readfile 内分配并初始化此参数。我对如何在子函数中处理 char** 有点困惑。

void main()
{
      char** data;
      readfile(data);
}

void readfile(char** data)
{
   data = (char**)malloc(1000);   //give me Segmentation fault
   data = (char*)malloc(1000); //give me " warning: assignment from incompatible pointer type" during compliation.
   data = (char)malloc(1000); //give me "warning: cast from pointer to integer of different size" during compilation.

}

我尝试先将指针转换到它,例如char* pdata = *data; 我可以使用 pdata 确定。

如何在 readfile 函数中分配此变量?

最佳答案

有两种解决方案:

  1. 在main中分配内存

  2. 像这样传递指针的地址:

    void main()
    {
        char** data;
        readfile(&data); //notice the pass of data adress to the function
    }
    
    void readfile(char*** data)  //notice the extra * operator added
    {
        *data = malloc(1000); 
    }
    

关于c - 如何在函数内初始化和分配 char** 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25534816/

相关文章:

c - 什么时候抛弃 const 合法还是非法? (gcc、clang 和 MSVC)

c++ - 指针指向一个我没想到的地址

c++ - 保留容量会导致两次分配还是一次分配?

java - 在具有更大内存的机器上运行时,java 会使用更多内存吗

使用指针的动态 LinkedList 的 push() 和 pop() 方法的 C++ 问题

c# - TimerCallback.PerformTimerCallback 内存分配

c - 用 strtok() 分割字符串会出错

c++ - 如何在 .cpp 文件中使用 C++ 关键字?

c - C 中的隐式数据类型转换

c - Linux内核修改指针值