c - 关于 C 语言中指针的相同输出

标签 c arrays pointers

下面是一段简单的代码:

#include <stdio.h>
#include <stdlib.h>

void main(void)
{
   int i,n=10;
   double *a;
   a = (double *)calloc(n,sizeof(double));
   if (!a){
       printf("Allocating error!\n");
       exit(1);
   }
   for (i=0;i<10;i++){
       printf("%f\n",*a++); /*Print 1*/
       printf("%f\n",a++);  /*Print 2*/
       printf("%f\n",a[i]); /*Print 3*/
   }
}

注意:三行打印是分开测试的,比如run printf("%f\n",*a++);/*打印 1*/ 并让其他两行作为注释行打印。

我的问题是:为什么三个不同的打印行有相同的输出?我的理解是 Print 2 和 3 具有相同的含义,但它们是地址... Print 1 有一个解引用符号 (*) 所以它是 double 字。我很困惑,谁能给个明确的解释?

附上编译信息:

warning: format ‘%f’ expects argument of type ‘double’, but argument 2 has type ‘double *’ [-Wformat=]
        printf("%f\n",a++);  /*Print 2*/

但奇怪的是:如果我直接执行代码而不是先调试它,没有错误并且它们都输出正确的结果(十个 0.000000)。

最佳答案

首先使用警告启用标志编译您的程序,如下所示,它可能会告诉您一些事情。

gcc -g -O -Wall test.c

这里是解释。

int  main()
{
        int i,n=10;
        double *a;
        a = (double *)calloc(n,sizeof(*a));/* use sizeof(*a) instead of sizeof(double) */
        if (!a){
                printf("Allocating error!\n");
                exit(1);
        }
        for (i=0;i<10;i++)
                printf("%lf\n",*a++); /* use %lf as a is of double ptr type
                                        it prints 0.00 everytimes not 1 as calloc zeroed 
                                        whole memory */

        /* when loop fails where a points ? */
        printf("%p\n",a++);  /* it prints address and use %p instead of %f */
        printf("%lf\n",a[i]); /* it results in undefined behaviour 
                                as you are trying to access out of boundry like a[11] 
                                which you didn't allocated */

        return 0;
}

关于c - 关于 C 语言中指针的相同输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49460693/

相关文章:

c - 警告 : Assignment from Incompatible Pointer Type [enabled by default] while assigning Function Address to Function Pointer

Python从内部函数更改外部字典

c - 旋转窗口的工具,如 cvmovewindow

c - 如何在非规范模式下从读取函数返回且 VMIN 和 TIME 不等于零

C 信号不能正常工作

php - 不确定如何随机化这个

c++ - 直接访问 boost::mapped_region 数据?

c - 正确释放动态分配的结构

将 LPVOID 类型与 char * 连接

javascript - 用数组检测运动范围