人生就是这样,笑笑别人,再被别人笑笑。之前笑过别人返回栈指针,没想到,我今天也返回了栈指针,我晕。

      别人程序是(有错误):

#include <iostream>
using namespace std;

char * fun()
{
	char str[] = "123";
	return str;
}

int main()
{
	cout << fun() << endl;
	return 0;
}

      其实,可以勉强改为:

#include <iostream>
#include <string>
using namespace std;

string fun()
{
	char str[] = "123";
	return str; // 最好是: return string(str);
}

int main()
{
	cout << fun() << endl;
	return 0;
}

      我今天居然写了这样一个程序,晕乎:

#include <iostream>
using namespace std;

void fun(char *s)
{
	char str[] = "123";
	s = str; // 错误
}

int main()
{
	char s[100] = {0};
	fun(s);
	cout << s << endl;

	return 0;
}

     应该写成:

#include <iostream>
using namespace std;

void fun(char *s, int n)
{
	char str[] = "123";
	strncpy(s, str, n - 1);
}

int main()
{
	char s[100] = {0};
	fun(s, sizeof(s));
	cout << s << endl;

	return 0;
}

     哎,不能大意啊。


本文转载:CSDN博客