C - Why does the 'address of' operator return an integer value of a variable, regardless of variable type?

Viewed 94

I was doing some practice with strings of different types and returning their address so I could understand the concept of pointer arithmetic better.

I noticed that when using the printf function, and %p as the reference character, the address would increment by 4 + 1 bytes when using the & operand on the variable, and by 1 byte without it.

Here is an example of my code and it's output:

 1 #include <stdio.h>
 2 #include <string.h>
 3 
 4 
 5 int main ()
 6 {
 7 char charString_1[] = "Hello";
 8 printf("%s\t%s\t %p\t %p\n", charString_1 + 1, charString_1 + 1, &charString_1 + 1, charString_1 + 1);

The output was the following ello ello 0x7ffe76aba5d0 0x7ffe76aba5cb

Looking at the last two hex numbers only, the address is 203 and 208 (in decimal) respectively. So the latter is a char + int value bigger than the former. if I increment by two (&charString_1 + 2) , the gap is now 2(char + int) = 10 bytes.

I understand this question might be ridiculous, but my search results have turned up nothing. I'm trying to understand how memory works, and become better at finding common faults in buggy code.

2 Answers

When you do arithmetic on a pointer, the 'base unit size' is the size of the object pointed to.

So, for char_string, which points to a char (size = 1), the + 1 operation adds just one.

However, the expression &char_string evaluates as a pointer to an array, which (in your example) has a size of six characters (including the nul terminator), so the + 1 operation on that adds 6.

The difference in values printed by your two %p fields (5) is the difference between those two sizes (6 - 1 = 5). If you change the length of the array (e.g. like char charString_1[] = "Hello, World!";) you will see a corresponding change in the value of &charString_1 + 1.

"+1" will add the size of one of whatever type the compiler determines it is working with. In one case it believes it is working with a char, so it will add one byte (one "sizeof" a char). In the other case, it determines it is working with a pointer, so it will add one "sizeof" a pointer (typically 4 bytes).

(Edit: See below for the correction by Eric Postpischil, who points out that it actually sizeof pointer vs sizeof array)

Related