下面是一些伪代码,但我正在努力实现这一点。问题如所写,它返回一个空指针。
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/