#include <iostream>
#include <string>
#include <stdio.h>
#include <string.h>
//定义一个结构体
struct test
{
int a;
};
int main()
{
using namespace std;
test *A;
A=(test*)malloc(sizeof(test));
A->a = 1;
cout<<A->a<<endl;
test *B=A;//B直接在定义的时候 等于A 不需要加malloc ; 也可以 先声明再定义test *B;B=A;
test *B_with_malloc=(test *)malloc(sizeof(test));
std::cout<<B_with_malloc->a<<endl; //输入为0 编译器自动设置为0
//B_with_malloc=A;
//上面产生内存泄露了
cout<<B_with_malloc->a<<" "<<B_with_malloc<<" "<<A<<endl;
cout<<B->a<<" ";
//内存拷贝 在保留指针的地址的同时 复制内存
memcpy(B_with_malloc,A,sizeof(test));//test占4B大小,所以sizeof(test)=4
cout<<B_with_malloc->a<<" "<<B_with_malloc<<" "<<A<<endl;
cout<<sizeof(test);
}
c++ 指针malloc和不malloc区别
最新推荐文章于 2024-02-28 16:18:54 发布