亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

請問如何修改才能讓程序正常運行?

請問如何修改才能讓程序正常運行?

C++
哈士奇WWW 2023-04-08 18:14:02
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’ returnedprojectv0.cpp:100: error: incompatible types in assignment of ‘char*’ to ‘char [16]’再請問 “warning: address of local variable ‘temp’ returned” 這個錯誤是怎么產生應該如何避免呢?謝謝啦 =w=
查看完整描述

3 回答

?
動漫人物

TA貢獻1815條經驗 獲得超10個贊

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


查看完整回答
反對 回復 2023-04-11
?
隔江千里

TA貢獻1906條經驗 獲得超10個贊

char* askForAString(void){    // 這里是申請的全局的動態內存
        char * temp = (char *)malloc(sizeof(char)*16) 
        //scanf("%s", temp);
        //fflush(stdin);
        return temp;
}
char password[16] = "evlos";char inputpsw[16];
inputpsw = askForAString(); //這里是第100行if (strcmp(password, inputpsw) == 0)
{        printf("Allowed!");
}free(inputpsw)


查看完整回答
反對 回復 2023-04-11
?
慕運維8079593

TA貢獻1876條經驗 獲得超5個贊

第一個函數的棧內存返回了。

問題不在返回上,問題在分配上。分配內存的語句是

char temp[16] = "";

temp數組是局部變量,局部變量是分配在棧上的。一個函數返回時,他的??臻g就會被釋放了。

要養成良好的內存管理習慣:面向過程的方法中建議,在A方法分配的內存就在A方法釋放;面向對象編程中建議A對象初始化的內存由A對象釋放。

而在第一個函數中用malloc分配內存(malloc在堆上分配)雖不會崩潰或者warning,但是不推薦。因為第一個函數作為內存分配者,卻沒能承擔釋放的責任(此責任轉交給第二個函數了)。如果還有函數3,函數4...函數100調用函數1,難道要函數2至函數100中都寫個free(xxx)嗎?如果有函數10000需要從函數100中返回字符串呢?工程大了以后,這樣的代碼很難維護。

我建議:C式編程管理裸奔內存,在方法二上分配buffer,buffer指針作為參數傳遞給方法一。方法二上用完buffer后及時釋放。


查看完整回答
反對 回復 2023-04-11
  • 3 回答
  • 0 關注
  • 193 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號