Warning about the wrong format in this program c

I try to compile this program without warning,

#include<stdio.h>
int main()
{
    int arr[] = {1,2,3};
    printf("value1 = %d value2 %d\n", *(&arr+1), *(arr+1));//here is the warning
    return 0;
}

But I get a compile time warning

warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat]

I am compiling my program on the ubuntu gcc version 4.6.3 64-bit compiler (Ubuntu / Linaro 4.6.3-1ubuntu5).

+4
source share
3 answers

&arraccepts the address of the array, this is a pointer to the array (not to be confused with a pointer to the 1st element). He has a type int(*)[3].

Then you do pointer arithmetic on that array pointer. Since it points to an array of 3 integers, it &arr + 1will mean "plus the size of one integer array", and you end up only specifying the declared array, which makes no sense.

*. . , , int*. int, , .

, , , &arr[0] + 1, arr + 1, .

+6

arr int (*)[3], int *, , &arr[0] , value2 .

, arr &, . &arr+1 &arr[0]+3. , sizeof &arr sizeof (int (*)[3]), 3. , value1 &arr[3], int *. &arr[3], arr[3], -, int (*)[3], .

, , .

. : , ?

+1

:

arr - "array 3 of int".

int arr[] = {1,2,3};

&arr " 3 int".

&arr + 1 " 3 int".

*(&arr+1) - " 3 int".

When an array is passed to a function, a conversion occurs. The address of the first element of the array is passed, not the array itself. In this case, it has a type int *.

"%d"waiting for a match int, so the compiler warns:

format '% d expects an argument of type' int, but argument 2 is of type 'int *

+1
source

Source: https://habr.com/ru/post/1625786/


All Articles