Search code examples
cpointerschardereference

Why does the char need to be dereferenced in this instance?


I've been doing some practice with trees in C for my undergraduate courses and I came about on very strange results.

This is the code that didn't output as expected. I have a tree with the root being the struct node * root, and the preorder function prints the data on each node on the tree.

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;
}

I was expecting the output to be "abdecfg", but instead the terminal is outputting a weird result, as such; https://i.imgur.com/LudpUn7.png . I get the GCC warning "[Warning] assignment makes integer from pointer without a cast", but I don't understand why. If I use the dereference asterisk on the char inputs, the error stops, and I get the expected output, like this;

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;
}

Please note that it does not work[1] if I put the dereference asterisk on the newNode input instead.

Thanks in advance for any help.


Solution

  • double quotes (") in C denote strings, which become char * (pointers). You want single quotes (') to get char constants.