Arun Joe Cheriyan
Arun Joe Cheriyan

Reputation: 215

Comparison of 1D and 2D Array Size in C

In C an array like int a[4] creates 5 locations to store integers including a[0] to a[4].

But in case of a 2D array like int a[2][2] is producing only four locations and not 3*3 = 9 locations. What is the reason for this?

Upvotes: 0

Views: 101

Answers (2)

sps
sps

Reputation: 2720

Your understanding of 1D array is incorrect. int a[4] reserves location for for 4 ints and NOT 5 ints.

i.e. int a[4] reserves memory for a[0], a[1], a[2], and a[3].

In case of 2D array, total elements is given by num of rows * num of columns, so yes a[2][2] contains 4 integers. So it reserves memory for 4 integers.

Upvotes: 3

Jashaszun
Jashaszun

Reputation: 9270

Invalid premise: in C, an array int a[4] creates 4 locations, not 5. If you're using a[4] afterwards, you're invoking undefined behavior via buffer overruns. The 2D array behavior is as expected.

Upvotes: 1

Related Questions