What is the type (ptr - A [0]) / (sizeof (A [0]) / sizeof (A [0] [0]))?

I have a 2D array Aand a pointer ptrpointing somewhere inside it. I know how to calculate the line number, but the actual type of the expression seems not portable:

#include <stdio.h>

int main(void) {
    int A[100][100];
    int *ptr = &A[42][24];

    printf("row number is %d\n", (ptr - A[0]) / (sizeof(A[0]) / sizeof(A[0][0])));
    printf("col number is %d\n", (ptr - A[0]) % (sizeof(A[0]) / sizeof(A[0][0])));
    return 0;
}

On OS / X, the compiler clangcomplains like this:

warning: format specifies type 'int' but the argument has type 'unsigned long' [-Wformat]

On Linux gccit gives a similar warning, but on Windows I get a different diagnostic:

warning: format specifies type 'int' but the argument has type 'unsigned long long' [-Wformat]

What is the actual type of this expression?

Is there any way to convey expression in printfwithout ugly casting?

+4
source share
2 answers

ptrdiff_t, , <stddef.h>. printf t. :

printf("pointer difference: %td\n", ptr - A[42]);

(sizeof(A[0]) / sizeof(A[0][0])) size_t, f - sizeof, <stddef.h>.

printf z. :

printf("array size in bytes: %zu\n", sizeof(A));

ptrdiff_t C, -65535 65535 , size_t 0 65535.

: a ptrdiff_t a size_t?

, 6.3.1.8. :

( ), . :

  • , . , , .

  • , , , .

  • , , .

  • , .

, ptrdiff_t size_t, :

: int , int, unsigned , unsigned, .

, size_t , int, size_t int, , , int ptrdiff_t (, int).

size_t - unsigned int, ptrdiff_t - int, ptrdiff_t unsigned int, unsigned int.

, size_t - unsigned int, ptrdiff_t - long int, size_t long int, , long int.

size_t - unsigned long int ptrdiff_t - long int (Linux OS/X 64-), ptrdiff_t unsigned long int, - unsigned long int.

size_t unsigned long long int ptrdiff_t long long int (Windows 64-bit), ptrdiff_t unsigned long long int, - unsigned long long int.

size_t ptrdiff_t, , long long int.

, : size_t ptrdiff_t.

printf:

:

printf("row number is %d\n", (int)((ptr - A[0]) / (sizeof(A[0]) / sizeof(A[0][0]))));

:

int row = (ptr - A[0]) / (sizeof(A[0]) / sizeof(A[0][0])));
printf("row number is %d\n", row);

( , size_t , unsigned long long):

printf("row number is %llu\n", 0ULL + (ptr - A[0]) / (sizeof(A[0]) / sizeof(A[0][0])));

, printf %zu size_t %td ptrdiff_t , size_t not ptrdiff_t. Windows, Microsoft C. - , MingW C gcc Windows: -D__USE_MINGW_ANSI_STDIO gcc printf, Microsoft.


: ptr - A[0] undefined, ptr , 6.5.6 :

  1. , ; .
+7

, , , , , . typedef.

++, auto std:: cout : , < <.

0

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


All Articles