Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

pointers

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
like image 932
Mos Moh Avatar asked Nov 28 '22 01:11

Mos Moh


2 Answers

  • 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].
like image 196
Lundin Avatar answered Dec 09 '22 14:12

Lundin


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.

like image 36
2501 Avatar answered Dec 09 '22 14:12

2501