2013-10-21 51 views
-1

假设我有一个char * str,但我不知道它的大小,所以我只能声明它。然后我把它传递给一个函数,这个函数会知道它的大小,所以它会初始化并设置它。我怎样才能做到这一点?C - 将未初始化的变量传递给函数

char * str; 
func(&str); 

void func(char ** str) { 
    // initialize str... 
} 
+1

downvoters - 只需一秒钟给一个理由。 – ryyker

+1

在为变量分配内存方面没有任何魔力。在某些时候,通过某种方法,您必须提供_size_值,以便可以正确调用诸如“malloc()”或“calloc()”之类的函数参数。 ***如果您发布了迄今为止的代码,并显示至少有一些努力来解决问题,那也不错。*** – ryyker

+0

谢谢,对不起。我添加了一些代码来为其他人澄清问题。 – sina

回答

2
#define SIZE 10 //or some other value 

const int SIZE = 10; //or some other value 

然后:

void init(char** ptr) // pass a pointer to your char* 
{ 
    *ptr= malloc(SIZE); //of any size 
} 

int main() 
{ 
    char *str; 
    init(&str); //address of pointer str 
    //...Processing 

    free(str); 
    return 0; 
} 
+0

我会upvote,如果你删除'sizeof(char)'... –

+1

@PaulGriffiths是的,我同意C定义'sizeof(char)'为1,总是(和C++也一样),但我认为OP是一个初学者,所以我补充说。无论如何,我会使用'char * ptr = malloc(SIZE * sizeof(* ptr));' – P0W

+0

+1'sizeof(* ptr)' – sina