c - *date = "星期天"; vs int *number = 7;
问题描述
我有这样一段代码:
#include <stdio.h>
int main(void)
{
char *date = "Sunday";
//int *number = 7;
printf("Today is %s, the 7 days of this week", date);
}
它按预期工作并打印
$ ./a.out
Today is Sunday, the 7 days of this week
尽管如此,当我取消评论时
#include <stdio.h>
int main(void)
{
char *date = "Sunday";
int *number = 7;
printf("Today is %s, the %d days of this week", date, *number);
}
它报告错误:
$ cc draft.c
draft.c:5:10: warning: incompatible integer to pointer conversion initializing 'int *' with an expression of type
'int' [-Wint-conversion]
int *number = 7;
^ ~
1 warning generated.
我的代码有什么问题?
解决方案
它应该是
int number = 7;
printf("Today is %s, the %d days of this week", date, number);
代替
int *number = 7;
printf("Today is %s, the %d days of this week", date, *number);
在第一个片段中,一个整数变量被初始化为 7 并打印它的值。在第二个片段中,一个指针被初始化为地址 7,然后打印内存地址 7 处的整数值。
推荐阅读
- python - 当数据库在容器中运行时,如何使用 alembic 自动生成和应用迁移?
- python - 502 错误网关 nginx
- textures - 仅烘焙纹理法线(Blender 2.92)
- c++ - C++ Malloc 不调用 mmap 或 brk?
- docker - 在 docker swarm 中使用 https 运行 gitlab 和 jenkins
- python - 将 3D numpy 矩阵重塑为 2D numpy 矩阵,保持行位置
- c++ - 非静态成员引用必须相对于特定对象 c++
- python - 如何替换数组的多个连续部分?
- angular - 更改后文本框未立即更新
- sql - 在连接表中使用 WHERE 子句时出现“列不存在”