首页 > 解决方案 > *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.

我的代码有什么问题?

标签: c

解决方案


它应该是

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 处的整数值。


推荐阅读