在 C++ 中显示访问冲突的错误
Error Showing Access Violation in C++
struct root
{
struct Qgroup
{
struct Qpost
{
struct Qcomment
{
struct Qcomment *next;
int likes;
int address;
} QComment[100];
int likes;
int comments;
int address;
} QPost[100];
int address;
int posts;
int users;
}QGroup[8];
}*Root = (struct root *)malloc(sizeof(struct root *));
在下一行获取访问冲突错误。
for(int i=0;i<5;i++)
Root->QGroup[i].address = i*128+1024*1024;
请帮我解决这个问题?
我尝试了静态分配和动态分配,但都未能读取上述循环中给出的数据。
此错误是从 main()
之后开始执行的
你的问题是内存分配:
malloc(sizeof(struct root *));
您为指针分配内存,在大多数现代系统上它只有 4 或 8 个字节。
首先我真的不觉得有必要在这里使用指针。
Root = malloc(sizeof(struct root *));
必须更正如下:
Root = (struct root *)malloc(sizeof(struct root ));
无需转换为 struct root *
,因为 malloc
returns 是一个空指针,您可以将其分配给 C 中的任何其他类型。但是对于 C++,您需要转换和你一样。
对于 C++,最好使用 new
和 delete
而不是 malloc
和 free
。
所以你可以简单的使用如下:
Root = new root ;
struct root
{
struct Qgroup
{
struct Qpost
{
struct Qcomment
{
struct Qcomment *next;
int likes;
int address;
} QComment[100];
int likes;
int comments;
int address;
} QPost[100];
int address;
int posts;
int users;
}QGroup[8];
}*Root = (struct root *)malloc(sizeof(struct root *));
在下一行获取访问冲突错误。
for(int i=0;i<5;i++)
Root->QGroup[i].address = i*128+1024*1024;
请帮我解决这个问题?
我尝试了静态分配和动态分配,但都未能读取上述循环中给出的数据。
此错误是从 main()
你的问题是内存分配:
malloc(sizeof(struct root *));
您为指针分配内存,在大多数现代系统上它只有 4 或 8 个字节。
首先我真的不觉得有必要在这里使用指针。
Root = malloc(sizeof(struct root *));
必须更正如下:
Root = (struct root *)malloc(sizeof(struct root ));
无需转换为 struct root *
,因为 malloc
returns 是一个空指针,您可以将其分配给 C 中的任何其他类型。但是对于 C++,您需要转换和你一样。
对于 C++,最好使用 new
和 delete
而不是 malloc
和 free
。
所以你可以简单的使用如下:
Root = new root ;