这里我的示例代码很好用:
//define struct
struct myStruct {
char *arrChar1;
char *arrChar2;
}
// code in Main
struct myStruct *structDeep1 = malloc( sizeof( struct myStruct *) );
structDeep1->arrChar1 = NULL;
structDeep1->arrChar2 = NULL;
structDeep1->arrChar1 = malloc( sizeof(char ) * 2); //2 char
if( structDeep1->arrChar1 == NULL) puts("trace error");
else puts("trace ok")
//stdout -> trace OK
没问题。
现在我的例子有一个奇怪的错误:
// define a second struct
struct myStructDeep2{
struct myStruct *structDeep1;
}
// next code in Main
struct myStructDeep2 structDeep2 = malloc( sizeof( struct myStructDeep2*) );
structDeep2->structDeep1 = malloc( sizeof( struct myStruct *) );
structDeep2->structDeep1->arrChar1 = NULL;
structDeep2->structDeep1->arrChar2 = NULL;
structDeep2->structDeep1->arrChar1 = malloc( sizeof(char ) * 2); //2 char
if( structDeep2->structDeep1->arrChar1 == NULL) puts("trace error");
else puts("trace ok")
//stdout -> trace error
在第二个指针中似乎是malloc函数write / crush。 我不明白我的代码中的问题在哪里,这很奇怪。
答案 0 :(得分:2)
当你这样做时:
structDeep2->structDeep1 = malloc( sizeof( struct myStruct *) );
你分配了一个指针的大小,但你想分配一个结构,所以你必须这样做:
structDeep2->structDeep1 = malloc( sizeof( struct myStruct) );
现在(假设malloc成功),你可以安全地做到:
structDeep2->structDeep1->arrChar1 = malloc( sizeof(char ) * 2);