Reputation: 379
Consider this program:
#include <stdio.h>
int main()
{
double *dp;
double **dpp;
dpp=&dp;
dp++;
dpp++;
return 0;
}
Suppose dp
has address 100 and dpp
has address 1000.
What will the address of these pointers be after incrementing?
Upvotes: 0
Views: 120
Reputation: 1420
double *dp
=> is pointer to variable of type double (size of dp
is 4 bytes only)
double **dp1
=> is a pointer to pointer which is pointing to double (size of dp1
is 4 bytes)
Pointer's size is always 4 bytes (assuming 32-bit machine; on a 64-bit machine, it's 8 bytes) i.e pointer size depends on how big the memory address is.
When you increment dp++
, you increment pointer pointing to double whose size is 8 bytes so it increments by 8 bytes (100 => 108).
When you increment the pointer to pointer, its size is 4 bytes so it increments by 4 bytes only (1000 => 1004)
Pointer increments depend on the type of object it is pointing at.
In your code you haven't declared a variable of type double
directly; you have initialized **dp1
which will will result in undefined behavior.
double a = 10.00;
dp = &a;
add the above two line to understand your code better (just one of the way).
Upvotes: 0
Reputation: 754920
The simplest thing is to make your program compilable and give it strictly defined behaviour, then run it.
#include <stdio.h>
int main(void)
{
double d[2] = { 3.141593, 2.718128 };
double *dp = &d[0];
double *dpa[2] = { &d[0], &d[1] };
double **dpp = dpa;
printf("dp = %p\n", (void *)dp);
printf("dpp = %p\n", (void *)dpp);
dp++;
dpp++;
printf("dp = %p\n", (void *)dp);
printf("dpp = %p\n", (void *)dpp);
return 0;
}
Note how the code carefully ensures that the pointers always point to valid data. You could extend the printing to print *dpp
(another pointer) and **dpp
and *dp
(both double values).
On my machine (Mac OS X 10.9.1, GCC 4.8.2, 64-bit compilation), the output is:
dp = 0x7fff56945510
dpp = 0x7fff56945520
dp = 0x7fff56945518
dpp = 0x7fff56945528
When compiled for 32-bit, the output is:
dp = 0xbfffc600
dpp = 0xbfffc5f0
dp = 0xbfffc608
dpp = 0xbfffc5f4
The jump of 8 in dp
is a consequence of sizeof(double) == 8
(for both 32-bit and 64-bit compilations). The change in dpp
of 4 for the 32-bit compilation and 8 for the 64-bit compilation is a consequence of sizeof(double *) == 4
for 32-bit and sizeof(double *) == 8
for 64-bit.
Upvotes: 3
Reputation: 281843
dp++
is undefined behavior, since dp
was never initialized. There are no guarantees about what will happen.
What will probably happen, though relying on this would be a poor decision, is that the numerical value in memory of dp
is incremented by sizeof(double)
, and the numerical value of dpp
is incremented by sizeof(double *)
. sizeof(double)
is probably 8, and sizeof(double *)
is probably 4 or 8.
Upvotes: 2