C - 将未初始化的变量传递给函数

标签 c function pointers initialization declaration

假设我有一个 char * str而且我还不知道它的大小,所以我只能声明它。然后我将它传递给一个函数,该函数将知道它的大小,因此它将初始化并设置它。我怎样才能做到这一点?

char * str;
func(&str);

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

最佳答案

#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;
}

关于C - 将未初始化的变量传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19502396/

相关文章:

C: 两个不同的数组指向同一个结构

c# - 错误调用函数,[对 PInvoke 函数的调用使堆栈不平衡]

计算函数内部数组中的元素

function - 在 Scala 中定义函数的两种方法。有什么不同?

php - Wordpress 表情符号禁用代码不起作用

c++ - 在函数定义之前引用字段

c++ - 从 int 类型的右值初始化 &Fraction 类型的非常量引用无效?

C++接受成员和外部函数指针

C 文本算法

c - 如何修复C程序中的Hook(堆栈的恢复)