This blog is under construction

Sunday 6 May 2012

What is an array?


  • Elements of similar data type grouped under a common name is known as an array.
  • Values present in an array can be identified using the subscript.
  • An array name is a pointer to the first element of an array.
Example:
int num[10];
Above is the declaration for an array of 10 integers where num is the name of the array and the value present inside the square bracket represents subscript of the arrray.

     int num[10];
     int *ptr;

     ptr = num; // Here, ptr points to first element of the array num.
     ptr++; // points to second element of the array num(num[1] is the second element).


Example C program using Arrays

#include <stdio.h> 
  int main() {
        // arr is an array of 5 elements
        int *ptr, i, arr[5] = {1, 2, 3, 4, 5};
        for (i = 0; i < 5; i++) {
                printf("%d ", arr[i]);  // prints array elements
        }
        printf("\n");

        // ptr points to first element of the array
        ptr = arr;
        printf("ptr: 0x%x\t&arr[0]: 0x%x\n", ptr, &arr[0]);
        for (i = 0; i < 5; i++) {
                printf("%d ", *(ptr + i));  // prints array elements using pointer
        }
        printf("\n");
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  1 2 3 4 5 
  ptr: 0xbf977824 &arr[0]: 0xbf977824
  1 2 3 4 5 



1 comment:

  1. Dell Laptop Service center are giving repair service at the door. We should high quality Dell out of warranty Laptop Repair, removal of virus, screen removal, wireless network set up, battery removal, motherboard replacement to several other are offered at budget friendly price and it’s Negotiable. We can fix them all in time by our well experience and certified technicians. If you want to repair your laptop in front of your eyesight, than you may call us: 7217871051

    ReplyDelete