通过函数给实参分配内存,可以通过二级指针实现
#include<stdio.h> #incldue<stdlib.h>void getheap(int *p) //错误的模型 {p = malloc(100); }void getheap(int **p) //正确的模型 {*p = malloc(100); } int main() {int *p =NULL;getheap(&p);free(p);return 0; }
如果出现以下错误:
test.c:6:7: warning: incompatible implicit declaration of built-in function ‘malloc’ [enabled by default]
*p = malloc(100);
是因为没有加上#include<stdio.h>的头文件。
以下的方法也是可以的
int *getheap() //正确的方法 {return malloc(100); }int main() {int *p =NULL;p = getheap();free(p);return 0; }
下面的写法是错误的:
char *getstring() //错误的写法 {char array[10] = “hello”;return array; } int main() {char *s = getstring();printf(“s = %s\n”,s);return 0; }
原因是:
char array[10] = “hello”; //栈变量,在函数调用结束之后便被释放掉了
下面方法返回结果可行:
#include<stdio.h>char *getstring() {char *p = NULL;p = "string";return p; }int main() {char *p = NULL;p = getstring();printf("p = %s\n",p);return 0; }
不涉及到内存分配:
char getstring() //正确的写法 {char c = ‘a’;return c; } int main() {char c= getstring();printf(“c = %c\n”,c);return 0; }
是正确的。
下面的写法也是可以的
const char *getstring() //正确的 {return “hello”; } int main() {const char *ss = getstring();printf(“ss = %s\n”,ss);return 0; }
常量在静态区,一直有效,直接返回地址是允许的。
可以将常量的地址返回值返回
或者:
char *getstring() //函数可以正确返回 {static char array[10] = “hello”; //在静态区域return array; } int main() {char *s = getstring(); }