请教C++中关于malloc()的问题
来源:百度知道 编辑:UC知道 时间:2024/06/20 17:45:37
我想把通过malloc()函数构造出的pn[]数组赋值,数据类型为int,pn[]长度为3,pn[0]=1,pn[1]=3,pn[2]=5
问题:在赋值过程中编译直接被中止,不显示赋值结果
请问为什么?
如果程序有问题,应该怎么写才正确?
程序如下:
在编译环境为VC++6.0下通过
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main()
{
int i;
int n=3;
int *pn=NULL;
pn=(int *)malloc(n*sizeof(int));
free(pn);
for(i=0;i<n;i++)
cin>>pn[i];
for(i=0;i<n;i++)
cout<<pn[i]<<endl;
getchar();
return 0;
}
不好意思,free(pn);这行删去不要
仍然不能输出所赋的值
请问原因所在 谢谢~
问题:在赋值过程中编译直接被中止,不显示赋值结果
请问为什么?
如果程序有问题,应该怎么写才正确?
程序如下:
在编译环境为VC++6.0下通过
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main()
{
int i;
int n=3;
int *pn=NULL;
pn=(int *)malloc(n*sizeof(int));
free(pn);
for(i=0;i<n;i++)
cin>>pn[i];
for(i=0;i<n;i++)
cout<<pn[i]<<endl;
getchar();
return 0;
}
不好意思,free(pn);这行删去不要
仍然不能输出所赋的值
请问原因所在 谢谢~
用TC++3.0软件把头文件#include <iostream>
改成#include <iostream.h>,再把using namespace std; 删除
是可以的用的
free(pn); //你这里free掉了这片内存,还怎么赋值,把这句去掉,正确的程序如下:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main()
{
int i;
int n=3;
int *pn=NULL;
pn=(int *)malloc(n*sizeof(int));
//free(pn); //你这里free掉了这片内存,还怎么赋值,把这句去掉,正确的程序如下:
for(i=0;i<n;i++)
cin>>pn[i];
for(i=0;i<n;i++)
cout<<pn[i]<<endl;
getchar();
return 0;
}
free(pn);这行最好就写,写在程序后面,养成良好习惯,要与mallco()配对出现
在我这里没出现问题- -||
1 3 5
1
3
5
Press any key to continue