malloc参数

指针变量大小与机器位数和编译器有关,因此在用malloc分配空间时,sizeof的参数应该是指针所指向的变量类型
例如:p=(pTest)malloc(sizeof(pTest))是错误的,因为pTest指向的类型是Test,这样会导致内存只分配8字节用于存储p指向的Test变量,而应该分配16字节;
正确写法:p=(pTest)malloc(sizeof(Test))。

//
// Created by dgm on 19-3-10.
//
#include <iostream>
using namespace std;
typedef struct {
    int i;
    int j;
    int k;
    int l;
}Test,*pTest;
int main()
{
    cout<< sizeof(Test)<<endl;
    cout<< sizeof(pTest)<<endl;
    return 0;
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_37613112/article/details/88379579