28.6.25

20250628 15:00 Array passing

  

← Previous 🏠 Homepage Next Chapter →
                                   

                                                



1. Passing Array Elements — One at a Time!




You can pass one box (element) from the array to a function:

Call by Value:

display(marks[i]);  // just sending the value
void display(int m) {
   printf("%d", m);  // m is just a copy
}

You’re giving the function a photocopy of the value. It can't change the original. 

Call by Reference:

disp(&marks[i]);  // sending the address
void disp(int *n) {
   printf("%d", *n);  // dereference and print the real thing!
}

You’re giving the function a key to the real box (memory address). 

2. Passing the Whole Array to a Function




Why send elements one by one when you can send the whole army? 

int num[] = {24, 34, 12, 44, 56, 17};
display(num, 6);  // OR display(&num[0], 6);
void display(int *j, int n) {
  for (int i = 0; i < n; i++) {
    printf("element = %d\n", *j);
    j++;  // move to next soldier
  }
}

Boom! You just passed the entire array using its base address.

3. Pointers + Arrays = Besties!



Pointers and arrays are like twins :

  • num[i] is the same as *(num + i)

  • Arrays live in contiguous memory (next to each other)

4. Pointer Magic Show



int num[] = {24, 34, 12, 44, 56, 17};
int *j = &num[0];

for (int i = 0; i < 6; i++) {
  printf("address = %u, element = %d\n", j, *j);
  j++;
}

Every time you do j++, it jumps to the next element (2 bytes ahead for int). It’s like hopping from box to box! 

Pointers Can Fight (And Compare!)



int *j = &arr[4];
int *k = arr + 4;

if (j == k)
  printf("Same location!");

Yes, you can compare pointers. But beware:
Don’t try pointer + pointer
Don’t multiply or divide them
It’ll confuse poor 'C' 

So, When to Use What?

Situation Use This
Access in fixed order     Use pointers 
Access randomly or complex logic     Use subscripts 
Want speed?     Pointers zoom! 



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 ...