This blog is under construction

Sunday, 6 May 2012

Array Declaration

Array declaration is similar to the ordinary variable declaration except that the array name will have information on number of elements it can hold.

Syntax:
     data_type array_name[subscript];
     data_type         - specifies the type of data that the array will hold
     array_name       - name of the array
     subscript           - specifies the number of elements it can accommodate

Example:
int arr[10];  //arr is an array of 10 integers


Example C program on array declaration

#include <stdio.h> 
  int main() {
        int i, num[10], *ptr;  // declaration for integer array num
        for (i = 0; i < 10; i++) {
                num[i] = i;  // assigning values to array elements
        }
        // assigning pointer ptr to the first element of the array
        ptr = num;
        printf("ptr: 0x%x  num:0x%x  &num[0]: 0x%x\n", ptr, num, &num[0]);
        for (i = 0; i < 10; i++) {
                // *(ptr+i) is equivalent to num[i]
                printf("num[%d]: %d\t*(ptr + %d): %d\n",
                                i, num[i], i, *(ptr + i));
        }
        return 0;
  }


  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  ptr: 0xbf8ecd70  num:0xbf8ecd70  &num[0]: 0xbf8ecd70
  num[0]: 0      *(ptr + 0): 0
  num[1]: 1      *(ptr + 1): 1
  num[2]: 2      *(ptr + 2): 2
  num[3]: 3      *(ptr + 3): 3
  num[4]: 4      *(ptr + 4): 4
  num[5]: 5      *(ptr + 5): 5
  num[6]: 6      *(ptr + 6): 6
  num[7]: 7      *(ptr + 7): 7
  num[8]: 8      *(ptr + 8): 8
  num[9]: 9      *(ptr + 9): 9



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