Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sizeof(arr+1) wrong output?

Tags:

c

There is something I can't understand in c. The following code:

#include <stdio.h>

int main(char* args){
    char abc[100];
    printf("%d %d", sizeof(abc), sizeof(abc+1));
}

outputs

100 4

I tought it should generate 100 100-1, which is:

100 99

Same for int abc[100]. It outputs

400 4

instead of

400 396

edit: Ok, so I saw your commands. abc+1 in an expression. therfore, the result is int, sizeof(int) == 4. So my other question is WHY in the first time I send a pointer for array and the result is the length of the array? The following:

int main(char* args){
    char abc[100];
    char *test;
    test = (char*)abc+1;
    printf("%d %d", sizeof(abc), sizeof(test));
}

Outputs 100 4

like image 596
Weiner Nir Avatar asked Feb 20 '26 09:02

Weiner Nir


1 Answers

The expression

abc+1 

is a pointer. Your pointers would therefore appear to be 4 bytes wide.

On the other hand, the expression

abc

is an array of char of length 100 and so its size is 100.

And as for the version using int instead of char, I'm sure you can now apply the above reasoning to explain the output.


I think your edit to the question essentially asks:

Why is abc+1 a pointer, and abc an array.

The standard says:

Other operands - Lvalues, arrays, and function designators (ISO/IEC 9899:201x 6.3.2.1/3)

Except when it is the operand of the sizeof operator, the _Alignof operator, or the unary & operator, or is a string literal used to initialize an array, an expression that has type "array of type" is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined.

So, when you write sizeof(abc) then abc does not meet the criteria required to convert the expression abc into a pointer. So abc is treated as an array. But in the expression sizeof(abc+1), abc+1 does not meet any of the listed exceptions and so is converted into a pointer.

Colloquially this is known as an array decaying to a pointer.

like image 168
David Heffernan Avatar answered Feb 22 '26 22:02

David Heffernan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!