69,368
社区成员
发帖
与我相关
我的任务
分享
strcpy(pM->aa,"test"); //没有为pM->aa这个指针初始化,需要在前面加上一句pM->aa = (char*)malloc(strlen("test")+1);
//另外看楼主的逻辑有点不知所去,到底想要干什么?
#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;
}
#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;
}
#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;
}