下面是一些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 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* testFunction(int size) {
char* p = malloc(size);
<do a bunch of stuff to assign a value>;
return p;
}
int runIt() {
char *str = 0;
int str_size = 100;
str = testFunction(str_size);
<do something>
free(str);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编辑
每个评论,也使大小成为输出.
char* testFunction(int *size) {
*size = <compute size>;
char* p = malloc(size);
<do a bunch of stuff to assign a value>;
return p;
}
int runIt() {
char *str = 0;
int str_size;
str = testFunction(&str_size);
<do something>
free(str);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
你已经接近第二个例子了,但是改变一下
int testFunction(char **t) {
...
t = malloc(100 + 1);
Run Code Online (Sandbox Code Playgroud)
到
int testFunction(char **t) {
...
*t = malloc(100 + 1);
Run Code Online (Sandbox Code Playgroud)
重点是您要传递 a char**,一个指向指针的指针,因此您希望将 malloc 分配给它所指向的内容(指针)。