What is meant by: int (*b)[100]
, and what is the clarification of this code to produce 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
int (*b)[100]
is an array pointer, a pointer that can point to an array of 100 int.*b[1] = 20;
is a severe operator precedence bug which reads beyond the bounds of the array. It should have been (*b)[1]
.int (*b)[100]
is a pointer to an int array of 100 elements. The variable b
points to allocated memory, which is allocated by malloc: malloc(100 * sizeof(int));
, but this allocates only one row.
The problem is in the next line: *b[1] = 20;
, this is identical to b[1][0]
, which is out of bounds of the array. This causes undefined behavior in the program.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With