关于用malloc函数给结构体分配空间的问题

软件和网站开发以及相关技术探讨
回复
been!!!
帖子: 16
注册时间: 2013-07-28 21:19
系统: Ubuntu 13.04

关于用malloc函数给结构体分配空间的问题

#1

帖子 been!!! » 2013-12-16 16:21

今日在做课程设计遇到了一些问题,我定义了一个结构体并用malloc函数分配空间时无法通过编译!
为了简单起见我把这个问题抽离出来。大家给我一点建议吧!

代码: 全选

#include "stdio.h"
#include "malloc.h"
typedef struct {  int leader;
int loder;
int tag;
}HT;



int main(  )
{  

HT p;
p=(HT)malloc(sizeof(HT));


}
以下是个g++ -Wall -O h.c 编译的结果

代码: 全选

|| h.c: In function ‘int main()’:
h.c|14 col 24| error: no matching function for call to ‘HT::HT(void*)’
h.c|14 col 24| note: candidates are:
h.c|6 col 2| note: HT::HT()
h.c|6 col 2| note:   candidate expects 0 arguments, 1 provided
h.c|6 col 2| note: HT::HT(const HT&)
h.c|6 col 2| note:   no known conversion for argument 1 from ‘void*’ to ‘const HT&’
头像
YeLee
论坛版主
帖子: 26406
注册时间: 2008-08-13 8:48
系统: Fundu i64
来自: 东海硇州,一双管钥。
联系:

Re: 关于用malloc函数给结构体分配空间的问题

#2

帖子 YeLee » 2013-12-16 16:39

代码: 全选

#include "stdio.h"
#include "malloc.h"
typedef struct {
    int leader;
    int loder;
    int tag;
} HT;

int main()
{
    HT* p;
    p=(HT*)malloc(sizeof(HT));
}
◎当我站在道德的高度上俯视别人的时候,发现自己是多么渺小。
♥执着但不偏激,反对而不排斥,坚决捍卫矛盾体的存在方式。
★★★天气预报★★★
fcitx-yatable一个可以使用的码表输入法
[教程]几个实例攻克软件编译难关
Gentoo Development Guide
字体相关
xep007
帖子: 871
注册时间: 2006-01-03 20:44

Re: 关于用malloc函数给结构体分配空间的问题

#3

帖子 xep007 » 2013-12-16 16:50

楼上正解。
头像
qgymib
帖子: 539
注册时间: 2010-04-02 16:44
系统: openSUSE 13.2 x64

Re: 关于用malloc函数给结构体分配空间的问题

#4

帖子 qgymib » 2013-12-16 21:51

malloc、realloc、calloc等申请内存的函数返回的都是指针
正在建设中的个人博客
been!!!
帖子: 16
注册时间: 2013-07-28 21:19
系统: Ubuntu 13.04

Re: 关于用malloc函数给结构体分配空间的问题

#5

帖子 been!!! » 2013-12-17 16:42

代码: 全选

typedef struct{
 LinkType head;
LinkType tail;
int size;
}OrderList
thank you ,在我的课程设计中定义的是这样的结构体,其中LinkType是指针类型
而我需要的只是一个 OrderList类型的变量pt,因此我用下面的语句给pt分配了空间

代码: 全选

pt.head=(LinkType*)malloc(sizeof(LinkType))
pt.tail=(LinkType)mallco(sizeof(LinkType))
头像
cifer
帖子: 140
注册时间: 2011-10-24 23:37
系统: Debian Wheezy
联系:

Re: 关于用malloc函数给结构体分配空间的问题

#6

帖子 cifer » 2013-12-17 17:40

命名是 C, 为啥要用 g++ 编译?
自由, 是对人一生最重要的东西.

终于给博客想了个清新脱俗的名字, 望星听雨

听说这里挂推能够涨 fo, 于是... @cifer
回复