0

I created array:

int main()
{
    int num[3] = {1, 2, 3}
    return 0;
}

I want to get element in place 1.

Why can not I get the element by this code?

printf("%d", *(num + (sizeof(int)*1)));

What is the different to this?

printf("%d", *(num + 1));
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
gal leshem
  • 551
  • 1
  • 6
  • 18

3 Answers3

2

I understand you thought incrementing the pointer using sizeof(int) will get you to the next member in the array. However, this is not how it works:

when you write:

printf("%d", *(num + 1));

the pointer advances to the next member in the array (it is an int pointer and therefore when you increment it, it advances sizeof(int) (which is usually 4) bytes). But when you write:

printf("%d", *(num + (sizeof(int)*1)));

you try to advance the pointer by 4 members (or 4*sizeof(int) bytes), which is out of the boundaries of your array.

1

for printf("%d", *(num + (sizeof(int)*1))); has (sizeof(int)*1)) which is 4 [size of int = 4]. num is of type int pointer, which means that the addition num + (sizeof(int)*1)) will get you to the fourth element of the array, which is out of bounds, because you initialized the array with just 3 elements.

  • 1
    `sizeof int` is not necessarily 4, e.g., on a 64-bit system it could be 8, and there are even systems (such as DSPs) where `CHAR_BIT` is not 8, i.e., sizes are not in units of 8-bit bytes. – Arkku Dec 18 '19 at 19:50
  • Indeed, I see your point and you are right. I could've express myself better. – Ianau Andrei Dec 19 '19 at 14:40
  • 1
    The first C compiler I ever used (Aztec C/6502 on an Apple][) had sizeof(int) == 2... – Chris Dodd Dec 20 '19 at 20:25
1

The operator sizeof gives the number of bytes needed for a given type. As such, this result will change depending on the type and machine, and will not be always equal to 1. For integers (32bit), generally, it will be 4 and you are trying to access num[5] which doesn't exist.

You can find more about sizeof for different types here.

Egodev
  • 91
  • 5