(* b) [0] vs * b [0] - Arrays and pointers

I am working on toy problems to understand the differences between pointers and arrays in C, and I stumbled upon the fact that I still cannot find or find the answer.

I have the following program

#include <stdio.h>

int main()
{
    int a[3][3] = {{1, 2, 3}, {4, 5,6}, {7, 8, 9}};
    int (*b)[3];

    b = a;

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

    b++;
    printf("%d %d %d\n", (*b)[0], (*b)[1], (*b)[2]);

    b++;
    printf("%d %d %d\n", (*b)[0], (*b)[1], (*b)[2]);

    return 0;
}

And when I compile and run it, I get the following:

me@mac: clang -g q.c -o q.o                                                                     
me@mac: ./q.o
1 2 3
1 4 7
4 5 6
7 8 9

My question is what is the difference between (*b)[0]and *b[0]? It seems that the former has a type int *, and the latter has a type int *[3]. How to interpret the operators *[]()for this?

+4
source share
6 answers

int (*b)[3]; - , , , . int *b[3], 3 .

b=a b, 2D- a, 1D-.

, . , "" , printf.

*b[0], [] , *, " 0, , ".

, , b : , . , sizeof(*b) , 3*sizeof(int) .

+3

, - .

(*b)[1] , , b[0][1], .

*b[1], , *(b[1]). , b[1][0].

+2

, (* b) [0] * b [0]?

int (*b)[3] ; - 3. , - ().

*b[3] - 3 . - [];

- ,

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

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

printf printf, .

b++ , printf, .

+1

(*b)[0] , . *((*b)+(0)).

*b[0] , . **((b)+(0)).

, **b int, .

0

b - 3 int s.

b = a;  

a . a - , - 3 int s.

b = &a[0];

, b a[0]. a[0] a[0][i]. *(*(a + 0) + i)= *(*(a) + i)= *(*a + i)= (*a)[i].
(*a)[i] a int (*)[3], b. a[0] (*b)[i].
,

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

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

printf("%d %d %d\n", a[0][0], a[0][1], a[0][2]);   

*b[0]. *b[0] *(b[0]). b[0] a[0], , , , b[0] a[0][0] *(b[0]). * () , &a[0][0]. , *b[1] *b[2] &a[1][0] &a[2][0].

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

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

printf("%d %d %d\n", &a[0][0], &a[0][1], &[0][2]);

, (*b)[0] *b[0] , int.

0

, , , .

(* b) [0] * b [0]?

, b 3 int a.

int (*b)[3] = a; // int a[3][3]

, , a b

int a[X][Y];     // in your example, X=Y=3
int (*b)[Y] = a; // this line probably gives some clue about what b is

precedence. [] *, ,

  • *b[0], b[0], int [Y], [Y] [X][Y], * (dereferences) int, int Y.
    ( ) - int a[0][0].

  • with the parents (*b)[0], *bit is evaluated first to give int [Y], first, then [0]gives the first of the int [Y].
    The result (or target) is int in a[0][0]. Again ... really?

But two [0]are not the same thing! The confusion comes from the exit *and [0]to the first element, however, the evaluation order is different in both cases.

0
source

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


All Articles