我有一个由 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
函数中分配此变量?
最佳答案
有两种解决方案:
在main中分配内存
像这样传递指针的地址:
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/