首頁  >  問答  >  主體

C++ 中碰到的一个类型转换问题

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=

PHPzPHPz2714 天前537

全部回覆(3)我來回復

  • ringa_lee

    ringa_lee2017-04-17 11:02:43

    #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");
    }

    回覆
    0
  • 天蓬老师

    天蓬老师2017-04-17 11:02:43

    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)

    回覆
    0
  • 高洛峰

    高洛峰2017-04-17 11:02:43

    第一个函数的栈内存返回了。。。

    问题不在返回上,问题在分配上。分配内存的语句是

    char temp[16] = "";

    temp数组是局部变量,局部变量是分配在栈上的。一个函数返回时,他的栈空间就会被释放了。

    要养成良好的内存管理习惯:面向过程的方法中建议,在A方法分配的内存就在A方法释放;面向对象编程中建议A对象初始化的内存由A对象释放。

    而在第一个函数中用malloc分配内存(malloc在堆上分配)虽不会崩溃或者warning,但是不推荐。因为第一个函数作为内存分配者,却没能承担释放的责任(此责任转交给第二个函数了)。如果还有函数3,函数4...函数100调用函数1,难道要函数2至函数100中都写个free(xxx)吗?如果有函数10000需要从函数100中返回字符串呢?工程大了以后,这样的代码很难维护。

    我建议:C式编程管理裸奔内存,在方法二上分配buffer,buffer指针作为参数传递给方法一。方法二上用完buffer后及时释放。C++式编程,字符串由对象管理,参考小龙的回答。

    如果楼主对我的答案投票+1我会很感激

    回覆
    0
  • 取消回覆