相关疑难解决方法(0)

如何在函数内部使用malloc并在C中返回指针?

下面是一些psudo,但我正在努力实现这一目标.问题是写的,它返回一个空白指针.

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;
}
Run Code Online (Sandbox Code Playgroud)

如果我有一个预定义的大小,例如char str [100] =""并且我不尝试malloc或释放内存后记录,这可以正常工作.我需要能够使尺寸变得动态.

我也试过这个,但似乎不知何故遇到了一个腐败的指针.

int testFunction(char **t) {
    int size = 100;
    t = malloc(100 + 1);
    t = <do a …
Run Code Online (Sandbox Code Playgroud)

c malloc function

2
推荐指数
2
解决办法
7896
查看次数

标签 统计

c ×1

function ×1

malloc ×1