帮看看哪错了

micosun6 2008-04-27 10:52:59
#include <string>
#include <iostream.h>

typedef struct _t
{
int num;
char * aa;
}
t;
void test()
{
char * c;
c=(char *) malloc (1000*sizeof(char));
t *pM=(t * )malloc (sizeof(c)*sizeof(t));
strcpy(pM->aa,"test");
pM->num=1;

}
main()
{
test();
return 0;
}
...全文
72 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
micosun6 2008-04-27
  • 打赏
  • 举报
回复
如果是这样呢
#include <string>
#include <iostream>
using namespace std;

typedef struct _t
{
int num;
char* aa;
}t;
t* pM;

void test(int n)
{

pM[n].aa = (char*)malloc(sizeof(char)*20);
strcpy(pM[n].aa,"test");
pM[n].num=1;
cout << pM[n].aa;
// 释放内存

}

int main()
{
pM = (t*)malloc(sizeof(t)*100); //一下就分配了100个,有时只需要30个,或者超过了100,再设大不是很麻烦.
for (int i=0;i<100;i++)
{
test(i);
}
free(pM->aa);
free(pM);
return 0;
}
大海啊全是水 2008-04-27
  • 打赏
  • 举报
回复

t *pM=(t * )malloc (sizeof(c)*sizeof(t));
有问题!!sizeof(c) = 应该是 4 sizeof(t)应该是8

t *pM =(t*)malloc (sizeof(t) + 1000*sizeof(char));

baihacker 2008-04-27
  • 打赏
  • 举报
回复
strcpy(pM->aa,"test");  //没有为pM->aa这个指针初始化,需要在前面加上一句pM->aa = (char*)malloc(strlen("test")+1);
//另外看楼主的逻辑有点不知所去,到底想要干什么?
独孤过儿 2008-04-27
  • 打赏
  • 举报
回复
哦,不好意思,没看仔细,抱歉,抱歉!

#include <string>
#include <iostream>
using namespace std;

typedef struct _t
{
int num;
char* aa;
}t;

void test()
{
t* pM = (t*)malloc(sizeof(t));
pM->aa = (char*)malloc(sizeof(char)*20);
strcpy(pM->aa,"test");
pM->num=1;
// 释放内存
free(pM->aa);
free(pM);
}

int main()
{
test();
return 0;
}
andy_cai 2008-04-27
  • 打赏
  • 举报
回复
晕倒,原来是延迟。。。。。。。
andy_cai 2008-04-27
  • 打赏
  • 举报
回复
pM->aa没分配空间
其他的就不说了

奇怪,回帖成功后瞬间关页面,回帖就失败了
shaoze5 2008-04-27
  • 打赏
  • 举报
回复
还有个问题啊,你自己加一下吧,申请的空间在最后都要释放一下了!
andy_cai 2008-04-27
  • 打赏
  • 举报
回复
pM->aa没分配空间
其他的不说了
shaoze5 2008-04-27
  • 打赏
  • 举报
回复

#include <string>
#include <iostream.h>

typedef struct _t
{
int num;
char * aa;
}
t;
void test()
{
char * c;
c=(char *) malloc (1000*sizeof(char));
t *pM=(t * )malloc (sizeof(c)*sizeof(t));
pM->aa =(char *) malloc (20*sizeof(char)); //这里没有给aa分配空间,你如何使用呢?
strcpy(pM->aa,"test");
pM->num=1;

}
main()
{
test();
return 0;
}
独孤过儿 2008-04-27
  • 打赏
  • 举报
回复

#include <string>
#include <iostream>
using namespace std;

typedef struct _t
{
int num;
char* aa;
}t;

void test()
{
// 你不需要care机器的字长,这个是编译器的事。你只要直接分配结构体的内存就行了
//char * c;
//c = (char *) malloc (1000*sizeof(char));
t* pM = (t*)malloc(sizeof(t));
strcpy(pM->aa,"test");
pM->num=1;
}

int main()
{
test();
return 0;
}

69,368

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧