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
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
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
No comments:
Post a Comment