like this:
void** a = calloc(4,4);
printf("%x,%x",a,a+1));
the result is
1516c0,1516c8
why the step is 8? I don't want use (char*) to convert the type,what should I do?
like this:
void** a = calloc(4,4);
printf("%x,%x",a,a+1));
the result is
1516c0,1516c8
why the step is 8? I don't want use (char*) to convert the type,what should I do?
Printing pointers with %x
isn't well-defined, you should use %p
instead.
a+1
performs pointer arithmetic on type void**
, meaning you get the byte size of the pointed-at item, a void*
. So depending on how large such a pointer is on your system, you'll get an address change accordingly. Apparently your system has 64 bit pointers (likely 64 bit address bus) hence 8 bytes.
Using absolute values to calloc
is fishy code overall. Not sure what you are trying to achieve with that.
If you want a type-generic pointer that can iterate through generic chunks of data byte by byte, the correct type to use is unsigned char*
. If you don't want to use that for some artificial reason, then tough luck - no can do.
As mentiond the size of void *
is 8 on your system so it goes 8 bytes forward. Any way, you just need to change some thing and you don't need to use char *
for this case. In addition, using %p
to print pointers is a better choice:
void** a = calloc(4, sizeof(void *));
printf("%p,%p",a,a+1));
I believe that you have a problem with understanding the difference between the physical addresses and the references. Pointer arithmetic in C is done using the objects referenced by the pointers. When you print the pointer using "%p" or "%x" (not good as it is wrong format) you get the physical (byte) address.
You probably use void **
because pointer arithmetics on void *
does not work on most compilers that do not have special extensions as gcc
.
If you want the address
to be increased by one simply use char *
pointer instead of void *
If you want to print the difference in pointer arithmetics (not physical bytes):
int main(void)
{
void **a;
printf("%" PRIiPTR "\n", a - (a+1));
}