首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

为什么出这样的结果呢?百思不得其解,该如何处理

2012-02-12 
为什么出这样的结果呢?百思不得其解源程序:#includestdlib.h#includeiostream.h#includeiomanip.h#i

为什么出这样的结果呢?百思不得其解
源程序:
#include   <stdlib.h>
#include   <iostream.h>
#include   <iomanip.h>
#include   <string.h>
#include   <stdio.h>

typedef   struct
{
                int   weight;
                int   parent,lchild,rchild;
                char   ch;
}HTNode   ,   *htree;

void   CreatTree(htree   *ht   ,   int   *f,int   x)
{
                int   i;
                int   j=0;

                for(i=0;i <x;i++)
              {
                cout   < < "i   = "   < <   i   < <endl;
            cout   < < "j   = "   < <   j   < <endl;
                        cout   < < "f[ " < <j < < "]   1   = "   < <   f[j]   < <endl;
                (*ht)[i].weight   =   f[j];
                cout   < < "weight   = "   < <   (*ht)[i].weight   < <endl;
              j++;

              }
}

main(){
                int   f[16]   =   {1,2,3,4,5,16,17,8,9,10,11,12,13,14,15,16};
        int   x   =   16;
                htree   HT;
                CreatTree(&HT,f,x);
        return   0;
          }
输出结果:
i   =0
j   =0
f[0]   1   =1
weight   =1
i   =1
j   =1
f[1]   1   =2
weight   =2
i   =2
j   =2
f[2]   1   =3
weight   =3
i   =3
j   =3
f[3]   1   =4
weight   =4
i   =4
j   =4
f[4]   1   =5
weight   =5
i   =5
j   =5
f[5]   1   =16
weight   =16
i   =6
j   =6
f[6]   1   =1
weight   =1
i   =7
j   =7
f[7]   1   =8
weight   =8
i   =8
j   =8
f[8]   1   =9
weight   =9
i   =9
j   =9
f[9]   1   =10
weight   =10
i   =10
j   =10
f[10]   1   =11
weight   =11
i   =11
j   =11
f[11]   1   =2
weight   =2
i   =12
j   =12
f[12]   1   =13
weight   =13
i   =13
j   =13
f[13]   1   =14
weight   =14
i   =14
j   =14
f[14]   1   =15
weight   =15
i   =15
j   =15
f[15]   1   =16


weight   =16
第七个和第十二个为什么不是17和12呢?

[解决办法]
//应该是这样写的吧
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <string>
#include <cstdio>
using namespace std;

typedef struct
{
int weight;
int parent, lchild, rchild;
char ch;
}HTNode , *htree;

void CreatTree(htree *ht , int *f, int x)
{
int i;
int j=0;
*ht = new HTNode[x];//这里应该先在堆中分配一段空间
for(i=0; i <x; i++)
{
cout < < "i = " < < i < <endl;
cout < < "j = " < < j < <endl;
cout < < "f[ " < <j < < "] 1 = " < < f[j] < <endl;

//没有上面那一个分配空间语句,你这下面的操作都是
//在未分配的内存上进行读写操作,会早成未定义的错误
//即不知道什么时候就会出错,这就是你的程序出错的原因
(*ht)[i].weight = f[j];
cout < < "weight = " < <(*ht)[i].weight < <endl;
j++;
}
}

int main(void)
{
int f[16] = {1, 2, 3, 4, 5, 16, 17, 8, 9, 10, 11, 12, 13, 14, 15, 16};
int x = 16;
htree HT;
CreatTree(&HT, f, x);
delete [] HT; // 这里要删除
return 0;
}

[解决办法]
在VC上运行都运行不了,停在(*ht)[i].weight = f[j];上面了,因为ht都没有分配内存的...

热点排行