如何对malloc函数内,用C返回指针? [英] How to malloc inside a function and return pointer in C?
问题描述
下面是一些psudo,但我试图做到这一点。问题是书面,它返回一个空指针。
Below is some psudo, but I'm trying to accomplish this. The problem is as written, it returns a blank pointer.
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;
}
这工作正常,如果我有一个predefined大小,如字符海峡[100] =的,我不尝试的malloc或免费的内存后记。我需要能够使大小动态虽然。
This works fine if I have a predefined size, such as char str[100] = "" and I don't try to malloc or free memory afterwords. I need to be able to make the size dynamic though.
我也试了这一点,但似乎不知何故碰到一个腐败的指针。
I've also tried this, but seem to run into a corrupt pointer somehow.
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;
}
谢谢!
推荐答案
您快到了与第二个例子,但变化
You're nearly there with the second example, but change
int testFunction(char **t) {
...
t = malloc(100 + 1);
要
int testFunction(char **t) {
...
*t = malloc(100 + 1);
问题的关键是,你要传递一个的char **
,一个指针的指针,所以你要到的malloc分配到什么点是:(a指针)。
The point being that you're passing in a char**
, a pointer to a pointer, so you want to assign the malloc to what that points at (a pointer).
这篇关于如何对malloc函数内,用C返回指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!