c - 为什么在这种情况下需要取消对 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]。
提前感谢您的帮助。
解决方案
C 中的双引号 ( "
) 表示字符串,它成为char *
(指针)。您需要单引号 ( '
) 来获取 char 常量。
推荐阅读
- swagger - Swagger API 描述不应该有额外的属性
- linux - 命令行“随机”?用于磁盘测试的可播种随机二进制数据
- javascript - CryptoJS:将加密结果转换为十六进制,然后再返回,则无法再解密数据
- sql - 如何在雪花的左外连接期间提取所有值(即使是那些不匹配的值)?
- django-autocomplete-light - django autocomplete light Uncaught TypeError: $ is not a function
- svelte - Svelte 测试库不会检测到组件更新
- wordpress - Woocommerce pre_get_posts 和 tax_query 未按预期工作
- ios - Swift:将数据传递给前一个视图控制器的协议和委托
- asp.net-core - 身份提供者发起的单点登录 - 获取用户信息
- java - Intellij Community Edition 在 schema.sql 文件上显示此错误,如我在此处放置的图像上所见