Shannon-Fano encoding

Shannon-Fano encoding

本文关键字:encoding Shannon-Fano      更新时间:2023-10-16

我一直在尝试对shannon-fano压缩进行编码,但我认为我在内存分配方面遇到了问题。它进入函数的第二次迭代,然后在崩溃

   nod *node=new nod;
   node->st=new nod;     
   node->st->st=NULL;
   node->st->dr=NULL;

该函数本应使用Divide et Impera创建二叉树,但第一次调用shannonFano(n->st,begin)时它崩溃了。我的推测是记忆的分配是错误的。集体点头{char*info;int*思考;int val;结构体nod*st,*dr;

void shannonFano(nod *n, int dim)
{     
  if (dim>1)
  {
 int begin=0;
 int end=dim;
 int b_sum=n->pondere[0];
 int e_sum=n->pondere[dim];
 nod *node=new nod;
 node->st=new nod;     
 node->st->st=NULL;
 node->st->dr=NULL;
 node->dr=new nod;     
 node->dr->st=NULL;
 node->dr->dr=NULL;
 while (begin !=end-1)
 {
  if (b_sum > e_sum)
      {end--;
       e_sum=e_sum+n->pondere[end];
       } else {
              begin++;
              b_sum=b_sum+n->pondere[begin];
              }
 }
 strncpy(node->info,n->info,begin);
 for (int i=0;i<begin;i++)
     node->pondere[i]=n->pondere[i];
     node->val=0;
     n->st=node;
 strncpy(node->info,&n->info[end],dim-end+1); 
 for (int i=end;i<dim;i++)
     node->pondere[i]=n->pondere[i];     
     node->val=1;      
     n->dr=node;
   shannonFano(n->st,begin);
   shannonFano(n->dr,dim-end+1);              
    }           
}

我不确定你想做什么,但我看到了问题。根据您的格式,您希望每次执行for循环后的三行,但只有第一行。您需要添加{}

我真的看不到100%的代码,以及它是如何执行的,所以如果我错了,不要对我大喊大叫,但这一行:

int e_sum=n->pondere[dim];

看起来可疑。这个数组是在哪里分配的?它的尺寸是暗淡的吗?如果是,最后一个元素将在pondere[dim-1];并且在dim中使用该值会导致未定义的行为,很可能会导致程序崩溃。

此外,你的for循环后面没有大括号,所以循环中只会执行它们后面的第一行,而你的缩进表明你正在尝试执行所有缩进的行(我相信每种情况下都有3行)