fatfat325 发表于 2010-8-26 12:44:59

问个C++的指针问题

本帖最后由 fatfat325 于 2010-8-26 20:56 编辑

怎么判断一个指针是否已被initialise?

我在Dev C++下用(p==NULL)的时候编译没错,不过运行的时候会Segmentation Fault。。。

最近网络down了 偷的网 只能晚上再来一次了

原问题在下面。。。只能把注释的地方修改,main()不能动

fatfat325 发表于 2010-8-26 12:46:03

#include <iostream>
using namespace std;
class Node {
    public:
      Node(int);
      void attL(Node *);
      void attR(Node *);
      int getH();
    private:
      int key;
      Node *left, *right;
};
Node::Node(int k) {
    key=k;
    left=NULL;
    right=NULL;
}
void Node::attL(Node *tree) {
    if (left==0)
      left=tree;
    else
      throw 'L';
}
void Node::attR(Node *tree) {
    if (right==0)
      right=tree;
    else
      throw 'R';
}
int Node::getH() {
    int l,r;
    if (left==0) 这里怎么改?
      l=0;
    else
      l=(*left).getH();
    if (right==0)
      r=0;
    else
      r=(*left).getH();
    if (l>r)
      return l+1;
    else
      return r+1;
}
int main() {
    Node n = {0,1,2,3,4,5,6,7,8}; // construct nodes
    for (int i = 1; i < 8; ++i) {
      int root, subtree;
      char LR;
      cin >> root >> LR >> subtree; // get indices of the node and the root node
      // of subtree, and whether it will become the
      // left or right subtree.
      try {
            if (LR == 'L') n.attL(&n);
            else n.attR(&n);
            cout << n.getH();
      }
      catch (char c) { cout << c;} // tree attachment violation
    }
    return 0;
}

backham7 发表于 2010-8-26 13:02:15

CSDN。。。IT行業已經對我永久關閉了三年。。。

我在左边 发表于 2010-8-26 13:42:21

CSDN吧。。抱歉我只会JAVA 不学有指针的东东。。

yeehya 发表于 2010-8-26 13:51:32

NULL和0是等价的吧。
代码应该没有问题,要么就是数据下标越界了。。

fatfat325 发表于 2010-8-26 17:41:37

pk帝 围观帝呢。。。求助啊。。。

Repel-CrossingX 发表于 2010-8-26 18:49:55

试试 if (!left)

后镜里的公路 发表于 2010-8-26 19:24:43

卧槽...........我试试看穿越三年回去问问我自己

Think 发表于 2010-8-26 19:45:45

木有学过C++只学过C的路过。。。

luo311 发表于 2010-8-26 19:47:35

路过围观……0=015
页: [1] 2 3
查看完整版本: 问个C++的指针问题