c - 如何在函数内部进行 malloc 并在 C 中返回指针?

标签 c function malloc

下面是一些伪代码,但我正在努力实现这一点。问题如所写,它返回一个空指针。

int testFunction(char *t) {
    int size = 100;
    t = malloc(100 + 1);
    t = <do a bunch of stuff to assign a value>;
    return size;
}

int runIt() {
    char *str = 0;
    int str_size = 0;
    str_size = testFunction(str);
    <at this point, str is blank and unmodified, what's wrong?>
    free(str);
    return 0;
}

如果我有预定义的大小,例如 char str[100] = "",并且我不尝试分配或释放内存,则此方法可以正常工作。不过,我需要能够使尺寸动态化。

我也尝试过这个,但似乎不知何故遇到了损坏的指针。

int testFunction(char **t) {
    int size = 100;
    t = malloc(100 + 1);
    t = <do a bunch of stuff to assign a value>;
    return size;
}

int runIt() {
    char *str = 0;
    int str_size = 0;
    str_size = testFunction(&str);
    <at this point, str is blank and unmodified, what's wrong?>
    free(str);
    return 0;
}

谢谢!

最佳答案

第二个例子就快完成了,但是需要改变一下

int testFunction(char **t) {
  ...
  t = malloc(100 + 1);

int testFunction(char **t) {
  ...
  *t = malloc(100 + 1);

重点是您要传递一个 char**,一个指向指针的指针,因此您希望将 malloc 分配给它所指向的内容(指针)。

关于c - 如何在函数内部进行 malloc 并在 C 中返回指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12791456/

相关文章:

c - OpenGL - 圆圈绘制不平滑

function - 分解功能的行为称为什么?

c - 关于函数内部的自由指针有点令人困惑

Javascript - 使相同的函数具有不同的输入

python - 5.3.2 : Function call in expression Python

c - 在指针上使用成员访问运算符

c - 使用 malloc 创建指向多个结构项的指针

c - 为什么我无法打印链接列表成员的值?

c - Visual Studio 2017 上忽略了 typedef

objective-c - 如何按位与 CFBitVector