Z00810020120164096COMP6047 (T) Pert 13&14 - Pointer and Arrays
Z00810020120164096COMP6047 (T) Pert 13&14 - Pointer and Arrays
Z00810020120164096COMP6047 (T) Pert 13&14 - Pointer and Arrays
• Array characteristics:
– Homogenous
All elements have similar data type
– Random Access
Each element can be reached individually, does not
have to be sequential
• Syntax:
type array_value [value_dim];
• Example :
int A[10];
A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] A[9]
– Example:
int B[8]={1, 2, -4, 8};
int B[5];
Error, why ?
B[5]={0,0,0,0,0};
A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] A[9]
12 27 15
A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] A[9]
• Example:
– int x=10, y=20;
– int *ptr; //ptr is pointer variable
– ptr = &x;
– ptr = &y;
• Example:
int Arr1[10];
Arr1[10] = {1, 2, 3, 4, 5}; // error
Arr1 = {1, 2, 3, 4, 5}; // error
Arr1[10] = 12; // error max 9
Arr1[0] = 23; // ok
int SIZE = 5;
void main() {
int i, j;
int n[SIZE] = {15, 9, 1, 7, 5};
for( i=0 ; i<= SIZE ; i++) {
printf("%5d ", n[i]);
for ( j=1; j<=n[i] ; j++) printf("%c","*");
printf("\n");
}
}
COMP6047 - Algorithm and Programming 20
Two Dimensional Array
• Syntax 2D Array:
type name_array[row][col];
• Example:
int a[3][4];
Column 0 Column 1 Column 2 Column 3
Row 0 a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ]
Row 1 a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ]
Row 2 a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ]
Column subscript
Array name
Row subscript
COMP6047 - Algorithm and Programming 21
Two Dimensional Array
• Initialization:
using rmo (row major order)
• Example: 1 2
• int b[2][2] = {1, 2, 3, 4 };
• int b[2][2] = { { 1, 2 }, { 3, 4 } }; 3 4
1 0
• int b[2][2] = { { 1 }, { 3, 4 } };
3 4
Output:
12345
10 20 30 40 50
100 200 300 400 500
COMP6047 - Algorithm and Programming 23
Three Dimensional Array
• Syntax 3D Array :
type name_array[row][col][depth];
• Example:
int x[3][2][4] = {{{1,2,3,4}, {5,6,7,8}},
{{11,12,13,14}, {15,16,17,18}},
{{21,22,23,24}, {25,26,27,28}}
};
void main() {
int x[4][3][5] = {{{1, 2, 3}, {0, 4, 3, 4}, {1, 2}},
{{9, 7, 5}, {5, 7, 2}, {9}},
{{3, 3, 5}, {2, 8, 9, 9}, {1, 2, 1}},
{{0}, {1}, {0, 1, 9}}
};
printf(“%5d”, x[2][1][3]);
}
Output : 1 2 3 5
• Syntax:
char array_name[value_dim];
• Example:
char name[40];
char ss[20]={‘B’,’I’,’N’,’U’,’S’}; //20
elements
char ss[ ]= {‘B’,’I’,’N’,’U’,’S’}; // 5
elements
strlen(“nana”); // 4
strcmp(“nana”, “nana”) // result 0
strcpy(s1,s2); // s1 = “xyz”, s2 = “xyz”
strncpy(s1,s2,2); // s1 = “xycdef”, s2 = “xyz”
strncpy(s1,s2,4); // if n>=strlen(s2) similar with
// strcpy() s1 = “xyz”
strcat(s1,s2); // s1=“abcdefxyz”, s2=“xyz”
strncat(s1,s2,2); // s1=“abcdefxy”, s2=“xyz”
s1 = “Happy”
s2 = “New Year”