2014-08-27 106 views
-1

我有一个readfile函数,调用main。标准是我必须通过char**readfile,我必须在readfile内分配和初始化这个参数。我对如何在子功能中处理char**有点困惑。如何在函数内初始化和分配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 ok。

如何在readfile函数内分配这个变量?

+0

我们不知道你的' readfile'想做的。你的代码不会读取任何文件! – 2014-08-27 18:50:23

+0

http://stackoverflow.com/questions/2838038/c-programming-malloc-inside-another-function – jamesdlin 2014-08-28 02:18:50

回答

1

解决办法有两个:

  1. 在主

  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); 
    } 
    
+1

感谢您的答复。要求是使用char **作为参数并在函数内部分配内存。我必须能够将阵列带回主体。 – user3037484 2014-08-27 19:02:44

+1

是的,这非常可爱,但是如果你需要传递一个指针指针,它就不能完成。如果你有一个指针指针,你的参数必须是char ***数据。 – Igor 2014-08-27 19:07:05

+0

谢谢。我将主要分配内存。我只能做char *数据。它正在工作。 – user3037484 2014-08-27 19:13:44

0

也许你想char*data=NULL;main然后在那里打readfile(&data);那里。任何对readfile内部正式参数data的更改都不会传播给调用方(因为传递参数时C具有call by value语义)。

此外,你应该总是测试结果malloc像例如,

data = malloc(1000); 
if (!data) { perror("malloc data"); exit(EXIT_FAILURE); }; 

,你或许应该初始化内存获得区域,可能使用

memset (data, 0, 1000); 

或简单地使用calloc获得清零的内存。

如果传递&datamain声明你的readfile正式的说法为char**ptr,做内部readfile*ptr = malloc(1000);等...

顺便说一句,你有没有考虑使用getline(3)?这可能是相关的。