请问如何修改才能让程序正常运行?

char* askForAString(void){	char temp[16] = ""; //这里是第81行
	//scanf("%s", temp);
	//fflush(stdin);
	return temp;
}
char password[16] = "evlos";char inputpsw[16];
inputpsw = askForAString(); //这里是第100行if (strcmp(password, inputpsw) == 0)
{	printf("Allowed!");
}
projectv0.cpp: In function ‘char* askForAString()’:
projectv0.cpp:81: warning: address of local variable ‘temp’ returned
projectv0.cpp:100: error: incompatible types in assignment of ‘char*’ to ‘char [16]’


再请问 “warning: address of local variable ‘temp’ returned” 这个错误是怎么产生应该如何避免呢?

谢谢啦 =w=


哈士奇WWW
浏览 112回答 3
3回答

动漫人物

#include&nbsp;<iostream>#include&nbsp;<list>#include&nbsp;<string>std::string&nbsp;askForAString(void){ std::string&nbsp;temp; getline(std::cin,&nbsp;temp); return&nbsp;temp; }int&nbsp;main(int&nbsp;argc,&nbsp;char*&nbsp;argv){ std::string&nbsp;password("evlos"); if&nbsp;(&nbsp;0&nbsp;==&nbsp;password.compare(askForAString())&nbsp;)&nbsp;{ std::cout&nbsp;<<&nbsp;"OK"&nbsp;<<&nbsp;std::endl; } system("pause"); }

隔江千里

char*&nbsp;askForAString(void){&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;这里是申请的全局的动态内存 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;char&nbsp;*&nbsp;temp&nbsp;=&nbsp;(char&nbsp;*)malloc(sizeof(char)*16)&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//scanf("%s",&nbsp;temp); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//fflush(stdin); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;temp; }char&nbsp;password[16]&nbsp;=&nbsp;"evlos";char&nbsp;inputpsw[16]; inputpsw&nbsp;=&nbsp;askForAString();&nbsp;//这里是第100行if&nbsp;(strcmp(password,&nbsp;inputpsw)&nbsp;==&nbsp;0) {&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;printf("Allowed!"); }free(inputpsw)

慕运维8079593

第一个函数的栈内存返回了。问题不在返回上,问题在分配上。分配内存的语句是char&nbsp;temp[16]&nbsp;=&nbsp;"";temp数组是局部变量,局部变量是分配在栈上的。一个函数返回时,他的栈空间就会被释放了。要养成良好的内存管理习惯:面向过程的方法中建议,在A方法分配的内存就在A方法释放;面向对象编程中建议A对象初始化的内存由A对象释放。而在第一个函数中用malloc分配内存(malloc在堆上分配)虽不会崩溃或者warning,但是不推荐。因为第一个函数作为内存分配者,却没能承担释放的责任(此责任转交给第二个函数了)。如果还有函数3,函数4...函数100调用函数1,难道要函数2至函数100中都写个free(xxx)吗?如果有函数10000需要从函数100中返回字符串呢?工程大了以后,这样的代码很难维护。我建议:C式编程管理裸奔内存,在方法二上分配buffer,buffer指针作为参数传递给方法一。方法二上用完buffer后及时释放。
打开App,查看更多内容
随时随地看视频慕课网APP