首页 > 解决方案 > 为什么在这种情况下需要取消对 char 的引用?

问题描述

在我的本科课程中,我一直在用 C 语言练习树,结果却很奇怪。

这是没有按预期输出的代码。我有一棵树,其根是 struct node * root,preorder 函数在树上的每个节点上打印数据。

struct node{
    char data;
    struct node * left;
    struct node * right;
};

struct node* newNode(char data){
    struct node* node = malloc(sizeof(struct node));
    node->data = data;
    node->left = NULL;
    node->right = NULL;
    return(node);
}

void preorder(struct node * root){
    //struct node * start = root;
    struct node * L;
    struct node * R;
    if(root!=NULL){
        printf("%c",root->data);
        preorder(root->left);
        preorder(root->right);
    }
}

int main(){
    struct node * root = newNode("a");
    root->left = newNode("b");
    root->right = newNode("c");
    root->left->left = newNode("d");
    root->left->right = newNode("e");
    root->right->left = newNode("f");
    root->right->right = newNode("g");
    preorder(root);
    return 0;
}

我原以为输出是“abdecfg”,但终端却输出了一个奇怪的结果;https://i.imgur.com/LudpUn7.png。我收到 GCC 警告“[Warning] assignment 从没有强制转换的指针中生成整数”,但我不明白为什么。如果我在 char 输入上使用取消引用星号,错误就会停止,我会得到预期的输出,如下所示;

int main(){
    struct node * root = newNode(*"a");
    root->left = newNode(*"b");
    root->right = newNode(*"c");
    root->left->left = newNode(*"d");
    root->left->right = newNode(*"e");
    root->right->left = newNode(*"f");
    root->right->right = newNode(*"g");
    preorder(root);
    return 0;
}

请注意,如果我将取消引用星号放在 newNode 输入上,它不起作用[1]。

提前感谢您的帮助。

标签: cpointerschardereference

解决方案


C 中的双引号 ( ") 表示字符串,它成为char *(指针)。您需要单引号 ( ') 来获取 char 常量。


推荐阅读