gpt4 book ai didi

c - 使用 free() 释放内存,其指针位于指向结构的指针内

转载 作者:太空宇宙 更新时间:2023-11-04 00:33:17 24 4
gpt4 key购买 nike

嘿!我知道问题的标题很可怕,但我仍然无法用单行表达问题!

所以我开始了:

有一个数据指针 DataPtr 指向动态分配的内存,另一个结构指针 StructPtr 也指向动态分配的结构。

而且这些都在另一个结构中,比如 OuterStructure。

有一个链表,其中包含指向 OuterStructure 的指针。

struct StructONE
{
int a;
char b;
float c;
};

struct InnerStruct
{
char a;
int b;
};

struct StructTWO
{
int Num;
char * DataPtr;
struct InnerStruct * StructPtr;
};

struct LinkList
{
int NodeNum;
int NodeType; /* To Indicate Whether Pointer is of StructOne or StructTwo */
void * Ptr; /* This can be of type StructONE or StructTWO */
struct LinkList * Next;

};

LinkList * Start;
void main()
{

/* Structure Declarations */
InnerStruct * InnerStructure;
StructONE * OneStruct;
StructTWO * TwoStruct;

/* Fill up all the Structure */
InnerStructure= (InnerStruct *)calloc(100,sizeof(InnerStruct));
InnerStructure->a='a';
InnerStructure->b=5;

OneStruct= (StructONE *)calloc(100,sizeof(StructONE));
TwoStruct= (StructTWO *)calloc(100,sizeof(StructTWO));

TwoStruct->Dataptr=(char *) calloc(10,sizeof(char));
TwoStruct->StructPtr= InnerStructure;



/* Add these to Linked List
void Add_to_Linked_List(int NodeNum,int NodeType,void *ptr)
*/
Add_to_Linked_List(1,1,OneStruct);
Add_to_Linked_List(2,2,TwoStruct);

/* Everything is Okey Till Here.
Now When I want to delete a node from linked list,
First I have to release Memory pointed by DataPtr and StructPtr. */

DeleteNode(1);

} /* End of Main */

DeleteNode的代码是这样的:

void DeleteNode(int Num)
{
LinkList * NodePtr,*TempNode;
NodePtr= Start;

while(NodePtr->NodeNum!=Num)
NodePtr=NodePtr->Next;

/* Now NodePtr points to desired node */
if(NodePtr->NodeType==1) /* Pointer is StructONE Type */
{
free(NodePtr->Ptr);
TempNode->Next=NodePtr->Next;
free(NodePtr);
return;
}
else
{
/* Now the Problem Begins....
In StructTWO type, I have to release Memory allocated for DataPtr as well Struct Ptr */
free((NodePtr->ptr)->DataPtr);
/* This Line Generates Error as
Error C2227: left of '->DataPtr' must point to class/struct/union/generic type */


}


}

我该怎么办??

我知道我写的代码很糟糕......但是必须写这么复杂!!:(

也感谢您阅读本文!!

最佳答案


#define STRUCT_ONE 1
#define STRUCT_TWO 2

struct LinkList
{
int NodeNum;
int NodeType;
union
{
StructONE * Ptr_One;
StructTWO * Ptr_Two;
};

};

................

if(NodePtr->NodeType==STRUCT_ONE)
{
free(NodePtr->Ptr_One);
TempNode->Next=NodePtr->Next;
free(NodePtr);
return;
}
else
{
free(NodePtr->Ptr_Two->DataPtr);
....
}

关于c - 使用 free() 释放内存,其指针位于指向结构的指针内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4215217/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com