28.6.25

20250629 09:00 Array things


← Previous 🏠 Homepage Next Chapter →
                                                          

                                            

Arrays: The Organized Wardrobe of C



Think of an array like a cupboard with multiple drawers. Each drawer has a number (called an index), and you can store your socks (values) inside!

int num[] = { 24, 34, 12, 44, 56, 17 };

num[0] means the 1st drawer, which has 24.
But here's the twist:
*(num + 0) is the same thing!
Even this works: 0[num] 
Yes, i[num] == num[i] — C is cool (and a little crazy!).

The Real Thing: Access Array in 4 Crazy Ways!



printf("%d", num[i]);
printf("%d", *(num + i));
printf("%d", *(i + num));
printf("%d", i[num]);

All print the same value. C is basically saying:
"Hey, I’m flexible — call me however you like!" 

2D Arrays: The Spreadsheet of 'C'



Imagine a school chart where each row is a student, and columns are their roll number and marks.

int stud[4][2] = {
  {1234, 56},
  {1212, 33},
  {1434, 80},
  {1312, 78}
};

Here:

  • stud[0][0] → Roll No. of student 1

  • stud[0][1] → Marks of student 1

Just like Excel — but with more semicolons and fewer colors 

Memory Trick: It’s All Linear!

Even though we think in rows and columns, C stores everything in a single line (row by row).
Like how noodles are packed — long and continuous 

Pointers + 2D Arrays = Magic!



*( *(s + 2) + 1 ) == s[2][1]

Don't worry, it's not Harry Potter spells 🪄 — it's just pointer magic!

  • s + 2 → Go to 3rd row (0-based)

  • *(s + 2) → Address of 3rd row

  • *( *(s + 2) + 1 ) → 2nd column of 3rd row

So basically: *( *(s + i) + j ) == s[i][j]
Boom! 

Pointer to an Array (aka GPS to a Row)



int (*p)[2]; // p is a pointer to an array of 2 ints

Now you can go row by row like a pro!

You get the address of each row:

p = &s[i]; // point to row i

Then use:

pint = p;

And access elements using:

*(pint + j)

Like saying, "Hey C, take me to row i, column j!" 

Passing 2D Arrays to Functions: 3 Flavors




Like ice cream, there are 3 ways:

1. Using a plain int* pointer:

* (q + i * col + j)

Calculate the exact spot like a math wizard. 

2. Using pointer to array:

int (*q)[4];

Move row-by-row, then jump to columns.

3. Using normal 2D array notation:

int q[][4];

Old-school and easy! Just say q[i][j].

All roads lead to Rome... or in this case, the array element. 

No comments:

Post a Comment

rating System

Loading...

Understanding Arrays in C

The Bookshelf Analogy & Book-Author Example Arrays are one of the most essential concepts in C programming. They let you store multiple ...