liv2hak
liv2hak

Reputation: 14970

Strange result with pointer arithmetic

I wrote the following program to understand pointer arithmetic. The second output seems strange since the pointer 'cp' is declared as a const char **.Without any casting I would expect it to increment by '1' when I do (cp + 1) instead of '8' as the output shows.

#include <stdio.h>

typedef const char uint8_t;

const char *c = "hello";
const char **cp = &c;
const char ***cpp = &cp;
const char ****cppp = &cpp;

int main() {

        printf(" cp     %p     (cp + 1)   %p \n",(int*)cp, ((int*)cp)+1 );
        printf(" cp     %p     (cp + 1)   %p \n", cp, (cp + 1));
        printf(" cp     %p     (cp + 1)   %p \n", (uint8_t*)cp, ((uint8_t*)cp) + 1);

        return 0;
}


 cp     0x601020     (cp + 1)   0x601024 
 cp     0x601020     (cp + 1)   0x601028 
 cp     0x601020     (cp + 1)   0x601021 

Upvotes: 3

Views: 103

Answers (2)

Caleb
Caleb

Reputation: 124997

Without any casting I would expect it to increment by '1' when I do (cp + 1) instead of '8' as the output shows.

You might expect that, but you'd be wrong. When you increment a pointer, the size of the increment is the size of the thing that the pointer points to, and in this case that's 8 bytes (the size of a pointer).

If you think about it for a minute, that make a lot more sense than incrementing by 1 byte. If you have a pointer to an array of things, whether those things are integers or other pointers or structs, it's useful to be able to get the n+1th item in the array by adding n. If pointers always incremented by 1 byte, you'd have to instead write something like: p += (n * sizeof(MyStructType));. Doing that would be harder to read in most cases and also more prone to errors. On the other hand, there's not much benefit to being able to increment a pointer to a structure by 1 byte -- it's a sure way to cause misalignment bugs.

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726489

Without any casting I would expect [const char **] to increment by '1' when I do (cp + 1) instead of '8' as the output shows.

No - a pointer to a pointer would increment by the size of a pointer, which on your system is 8.

Upvotes: 4

Related Questions