Like this type (int (* ptr) [3]) = a; (where a is => int a [] [3] = {1,2,3,4,5,6}) of operators working in C? The increment "ptr" gives an unexpected result

For the following code:

#include <stdio.h>
int main()
{
    int a[][3] = {1, 2, 3, 4, 5, 6};
    int (*ptr)[3] = a;
    printf("%d %d ", (*ptr)[1], (*ptr)[2]);
    ++ptr;
    printf("%d %d\n", (*ptr)[1], (*ptr)[2]);
    return 0;
}

what should he print? I expect:

2 3 3 4

but conclusion:

2 3 5 6

I expect the output to be 2 3 3 4 because it initially ptrpoints to the first row of a two-dimensional array a[][3]. Therefore the (*ptr)[1]first printf will give us 2how wise (*ptr)[2]will give us 3. But after the line, ++ptrit will begin to point to the second element of the first line a[][3]. Therefore, the (*ptr)[1]second line should now give us 3, and also (*ptr)[2]should give us 4.

+4
3

ptr int (*)[3]:

int (*ptr)[3]

ptr , ptr.


:

int *p;
// ...
int (*ptr)[N] = p;
ptr += M; // same address as p[M * N]

M M * N * sizeof(int), M * sizeof(int), .

, ptr int [N], int.


++ptr;, ptr a. int , .. N = 3.

+5

.


int a[][3] = {1, 2, 3, 4, 5, 6};

a " 3 int".

int a[][3] = {{1, 2, 3}, {4, 5, 6}}; /* alternate */

, a - . .

int (*ptr)[3] = a;

ptr " 3 int". - - ptr a (int (*ptr)[3] = &a[0]).

printf("%d %d ", (*ptr)[1], (*ptr)[2]);

ptr a[0],

2 3

++ptr;

, . , , . , ( 3 int s, int). , 3 int ( a[1]).

printf("%d %d\n", (*ptr)[1], (*ptr)[2]);

, , ptr a[1], , (*ptr)[1] a[1][1], 5; (*ptr)[2] a[1][2], 6. , :

2 3 5 6


+4

(*ptr)[3] - . .

#include<stdio.h>

int main()
{
    int a[][3] = {1, 2, 3, 4, 5, 6};
    int (*ptr)[3]=a;
    /* First note ptr is a pointer to an array of three integers
     * If you had written it like 
     * int (*ptr)[3];
     * ptr=&a[0];
     * ,it would have been more obvious.
     * But here, you have the freedom to use it interchangeably
     */

    printf("%d %d ", (*ptr)[1], (*ptr)[2]);
    /* Remember ptr is &a[0], so *ptr is dereferencing &a[0] to gets its value
     * However, since ptr is a pointer to an array, its value itself is an array
     * So you need to give the index like (*ptr)[1] & (*ptr)[2] to get the second and third values
     * (Mind the count starts with zero)
     * In essence you are doing,
     * printf("%d %d ", *((*ptr)+1*4*8),*((*ptr)+2*4*8)); // 4bytes=4*8 bits
     * Here '*ptr' will be substituted with a[0],the starting address an 12 byte block ( 3 integers * 4 bytes per integer)
     */
    ++ptr;
    /* Above step can be written as
     * ptr=ptr+1; 
     * This is pointer arithmetic, so '1' above should be considered as 1 block
     * Or in layman terms move pointer to the next 12byte block.
     * In other words advance ptr by (12*8) bits so that it now points to &a[1]
     */
    printf("%d %d\n", (*ptr)[1], (*ptr)[2]);
    /* Follow the same steps for the first print with ptr is &a[1]
     */
    return 0;
}
+2

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


All Articles