What is meant by: int (* b) [100]

What is meant by: int (*b)[100]and what does this code explain to get this result?

#include <iostream>
void foo(int  a[100])
{
    a [1]= 30 ;
    std::cout<<a[1]<< std::endl;
}

void boo(int a[100])
{ 
    std::cout<<a[1]<< std::endl; 
}

int main()
{
    int (*b)[100] = (int (*) [100]) malloc(100 * sizeof(int));
    *b[1] = 20;
    std::cout<< *b[1] << "\t" << b[1] << std::endl;
    foo(*b);
    boo(*b);
    std::cout<< *b[1] << "\t" << b[1] << std::endl;
}

The above code outputs:

20  0x44ba430
30
30
20  0x44ba430
+4
source share
6 answers

int foo[100];declares fooas an array of 100 int. Type foo- int [100](just remove foo from its declaration).

int (*b)[100];declares *bas an array of 100 int. And that means that it bis a pointer to such an array. So you can write b = & foo; eg. The type bis equal int (*)[100](again, just remove b from its declaration).

, , , foo (.. int) foo. . b int [100]. :

b = (int (*) [100]) malloc(25 * sizeof(int [100])); // allocates an array of 25 int [100]
b[0][99] = 99; // correct
...
b[24][99] = 24099; // correct
b[24][100] = 24100; // incorrect because each b[i] is an array of 100 integers
b[25][0] = 25000; // incorrect because b is an array of 25 elements (an each element is an array)

, , int [100] (, 100 * sizeof(int) == sizeof(int [100])). , :

b[0][0] = 0;
*(b[0]) = 0;
*b[0] = 0;

*b[1] .

+3
  • int (*b)[100] - , , 100 int.
  • *b[1] = 20; - , . (*b)[1].
+13

int (*b)[100] - 100 . b , malloc: malloc(100 * sizeof(int));, .

: *b[1] = 20;, b[1][0], . undefined .

+4

int (* b) [100]; int * b [100];

int (*b)[100]; // A pointer to an array of 100 integers.

int *b[100]; // An array of 100 int pointers.
+3

int (*b)[100] b 100 .

malloc , b. *b , , . b[1] - , b + 1. 100 , b .

foo pointer to int 30 , ( ). foo boo , .

std::cout<< *b[1] << "\t" << b[0] << std::endl;

and look at the difference in what address b[0]and what address b[1], you will find that they are separated by 100 integers. In my compiler, I see the difference in 0x190, which is 400 bytes (an integer is 4 bytes and 100 integers is 400 bytes).

+2
source

I prefer to understand strange statements by first typing them and then trying to connect and see.

For example,

typedef unsigned char uint8_t; // 8 bit memory
typedef uint8_t b[100]; // create an array b having 100 elements,
                        // where each element occupies 8 bit memory
typedef uint8_t *e;//create a pointer that points to a 8 bit memory

main()
{
 b *c; //create a pointer c pointing to a type b-"array having 100 elements
       // & each element having 8 bit memory". This is equivalent to what 
       // you said - (*b)[100]. Like just moving the *
 b d;//create an array d having 100 elements of 8 bit memory
 e f[100];//create an array of 100 pointers pointing to an 8 bit memory
} 

It may also help.

0
source

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


All Articles