C++问题,大侠指点哈,谢谢。

来源:百度知道 编辑:UC知道 时间:2024/05/15 09:37:52
#include<iostream.h>
#include<string.h>
#include<stdlib.h>

void main()
{
char *p = (char *) malloc(100);
strcpy(p, "hello");
free(p);
strcpy(p, "world");
cout<<p<<endl;
}

#include<iostream>
#include<string>
#include<stdlib.h>
using namespace std;
void main()
{
char *p = (char *) malloc(100);
strcpy(p, "hello");
free(p);
strcpy(p, "world");
cout<<p<<endl;
}
程序的结果为什么不一样?
为什么用了命名空间和不用结果是不一样的?不用的时候是“W屯屯”,用了命名空间是“world”?书上还说在释放指针后strcpy(p, “world”); 语句会出错,为什么用了命名空间时能正常输出?

using namespace std; 的问题 具体我也搞不懂 你看看一些链接http://zhidao.baidu.com/question/15410807.html

该程序时有错的,但也许能正常运行。
输出的结果可能不确定,如果能稳定输出,运行的结果应该没有区别。
当然,从应用库的角度看,他们不同的,第二个程序使用了名称空间。

一样

你把申请的内存释放掉了,p成了野指针,可能指向操作系统内存的任何可能的地方,然后你非法的将字符串copy到你自己无法控制的地方有可能根本就没成功,在运行时没出错就不错了。程序结果不一样正常得很

你的程序不严谨