在linux写结构体时遇到一个警告
hw_vote_struct_pint_func_arry.c:53:9: warning: function returns address of local variable [-Wreturn-local-addr]
53 | return pV;
^
源代码:
struct Vote* readInf(int* numCan){
puts("enter the number of voter:");
scanf_s("%d",numCan);
struct Vote pV[* numCan];
for(int i=0;i<*numCan;i++){
pV[i].No = i+1;
printf("Enter the name of %d candidate:\n",i+1);
scanf_s("%s",pV[i].name);
pV[i].ballot = 0;
}
return pV; //返回首地址
}
这是定义的一个结构体指针函数,在当中定义了结构体数组pV用作初始化信息录入,初始化完成函数返回结构体数组的首地址,程序就警告返回局部变量。
原因:
局部变量存放在栈区,只有在所在函数被调用时才动态地为变量分配存储单元,所以生命周期只在函数调用期间,函数结束调用后其内存空间会被释放,意味着没有这块定义在函数中的存储空间。在本此错误中,函数调用后pV就没有了,返回它的地址其实里面没有东西
此处不同于以往的函数返回值(脑子混乱的我纠结了会儿),如函数2,函数结束后返回的其实是123 这个值,不是c这个变量因为这个变量在函数调用结束后就释放了;对于函数1,返回了变量c的地址,但是这个变量调用就没了,换句话说就是内存里都没有c了,更别说用c的地址(打个不恰当的比喻:一头猪已经被吃完了,就不可能去找这个猪在哪个屠宰场里)
//函数1
// int* func1(){
// int c = 777;
// return &c;
// }
//函数2
int func2(){
int c = 123;
return c;
}
int main(){
// int* a = func1(); ;
//printf("%d",*a);
printf("%d",func2());
return 0;
}
解决方法:
- malloc
malloc给变量在堆分配了内存空间以后,其生命周期跨越了整个程序的执行,变量无了但是里面的内容还在分配的堆空间中,问题解决
struct Vote* readInf(int* numCan){
puts("enter the number of voter:");
scanf_s("%d",numCan);
struct Vote *pV = (struct Vote *)malloc(*numCan*sizeof(struct Vote));
for(int i=0;i<*numCan;i++){
pV->No = i+1;
printf("Enter the name of %d candidate:\n",i+1);
scanf_s("%s",pV->name);
pV->ballot = 0;
pV++;
}
return pV-(*numCan); //返回首地址
}