段错误(核心转储),请帮助。我不明白我做错了什么。代码编译但我得到上面的错误。我知道代码试图访问它不能访问的内存,但我看不到它发生在哪里。
#include <stdio.h>
#include <stdlib.h>
int freq[256] = {0};
struct Node
{
unsigned char m_ch;
int m_freq;
struct Node *m_ls,*m_rs;
struct Node *m_hls,*m_hrs;
};
struct Node* createNode(int freq,char ch);
void insertTree(struct Node **root,struct Node * n);
struct Node* getBinTree(FILE *fsrc);
void inorder(struct Node *root);
int main()
{
FILE *fsrc;
struct Node *tree=NULL;
fsrc = fopen("src.txt","rb");
tree=getBinTree(fsrc);
inorder(tree);
return 1;
}
struct Node* createNode(int freq,char ch)
{
struct Node *pNode=NULL;
pNode->m_freq=freq;
pNode->m_ch=ch;
return pNode;
}
void insertTree(struct Node **root,struct Node *n)
{
if(!(*root))
{
*root=n;
return;
}
if(n->m_freq<(*root)->m_freq)
{
insertTree(&(*root)->m_ls,n);
}
else
{
insertTree(&(*root)->m_rs,n);
}
}
struct Node* getBinTree(FILE *fsrc)
{
struct Node *temp=NULL;
struct Node **root=NULL;
int c,i;
while ((c = fgetc(fsrc)) != EOF)
{
freq[c]++;
}
freq[255]=1;
fclose(fsrc);
for(i=0;i<256;i++)
{
if(freq[i]>0)
{
temp=createNode(freq[i],i);
insertTree(root,temp);
}
}
}
void inorder(struct Node *root)
{
if(root != NULL)
{
inorder(root->m_ls);
printf(" %d\n",root->m_freq);
inorder(root->m_rs);
}
return;
}
最佳答案
struct Node *pNode=NULL; pNode->m_freq=freq;
其中一个原因是取消引用上面引用的代码块中的 NULL 指针。
在使用指针之前必须先分配内存。像这样:
struct Node *pNode = malloc (sizeof *pNode);
关于c - 树结构分割错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29950949/