函数中返回指针及关键字static:
int* func(); //函数声明,或叫函数原型。
int main(){int* n = func();printf("n = %u\n", n);return 0;
}int* func(){int n1 = 100; //函数结束时,n1被回收//static int n1; //加上static关键字,函数结束时不会被回收return &n1; //返回指针
}
上面结果运行时会报错,为什么?怎么解决?
- 原因:因为函数中的变量是相互独立的,即使变量名称一样。因此func函数结束时,变量n1被回收。
- 解决:若不想让变量n1被回收,可在变量n1前面加上关键字static即可
函数名返回多个变量,就像:scanf("%d%d", &d1, &d2);
void mfunc(int** a, int** b){int x = 100;int y = 200;*a = &x; //返回指针*b = &y;
}int main(){int* a = NULL; //由stdio.h中定义 #define NUL