0

Despite using double as datatype and correct format specifiers the output does not print the correct variable addresses output consists of just zeros

#include <stdio.h>

void main() {
    double a[5] = { 6.0, 7.0, 8.0, 9.0, 10.0 };
    double *p;
    p = a;
    printf("%lf \n", p);
    for (int i = 0; i < 5; i++) {
         printf("%lf \n", p++);
    }
}

Output:

0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
chqrlie
  • 131,814
  • 10
  • 121
  • 189

3 Answers3

0

I fixed it with 2 simple changes, described in the comments.

#include<stdio.h>
void main()
{
    double a[5]={6.0,7.0,8.0,9.0,10.0};
    double *p;
    p=a;
    printf("%p \n",p);       // Changed formatter to %p  to print addresses
    for(int i=0;i<5;i++)
    {
         printf("%p \n",p++); // Changed formatter to %p to print addresses
    }
}

Output

0x7fffdd887250 
0x7fffdd887250 
0x7fffdd887258 
0x7fffdd887260 
0x7fffdd887268 
0x7fffdd887270 
abelenky
  • 63,815
  • 23
  • 109
  • 159
0

These calls of printf

printf("%lf \n",p);

and

printf("%lf \n",p++);

invokes undefined behavior because there is used the wrong conversion specifier "%lf" (where by the way the length modifier has no effect even when used with object of the type double) with pointers.

Either you should use the conversion specifier %p like

printf("%p \n", ( void * )p);

and

printf("%p \n", ( void * )p++);

Or if you want to output addresses as integers you can include headers <stdint.h> and <inttypes.h> (the last header already includes the first header and write

#include <stdint.h> #include <inttypes.h>

//...

printf("%" PRIuPTR "\n", ( uintptr_t )p);

and

printf("%" PRIuPTR "\n", ( uintptr_t )p++);

Pay attention to that according to the C Standard the function main without parameters shall be declared like

int main( void )

Here is a demonstration program.

#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>

int main( void )
{
    double a[] = { 6.0, 7.0, 8.0, 9.0, 10.0 };
    const size_t N = sizeof( a ) / sizeof( *a );

    double *p = a;


    printf( "%p", ( void * )p );
    printf( " <-> %" PRIuPTR "\n", ( uintptr_t )p );

    for ( size_t i = 0; i < N; i++ )
    {
        printf( "%p", ( void * )p );
        printf( " <-> %" PRIuPTR "\n", ( uintptr_t )p++ );
    }
}

The program output is

00AFFE40 <-> 11533888
00AFFE40 <-> 11533888
00AFFE48 <-> 11533896
00AFFE50 <-> 11533904
00AFFE58 <-> 11533912
00AFFE60 <-> 11533920
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

maybe make the printf of for loop like this:

for(int i=0;i<5;i++)
{
printf("%lf \n",p[i]++);
}

OUTPUT:

0.000000         
6.000000         
7.000000         
8.000000         
9.000000         
10.000000
buddemat
  • 4,552
  • 14
  • 29
  • 49