Tuesday, September 27, 2011

Pointer and Array

In this exercise, an array of int and another array of char are created. On the other hand, a pointer to int and a pointer to char is defined. And then the pointers are assigned to the address of the arrays, and the elements of the array can be accessed by *(pointer + offset).

Pointer and Array

#include <iostream>

using namespace std;

const int LEN = 10;
int A_int[LEN];
int* ptA_int;
char A_char[LEN];
char* ptA_char;

int main()
{
cout << "Pointer and Array" << endl;

int i;
char c;

for (i = 0, c = 'a'; i < LEN; i++, c++){
A_int[i] = i;
A_char[i] = c;
cout << A_int[i] << "/" << A_char[i] << " ";
}
cout << endl;

ptA_int = A_int;
ptA_char = A_char;
for (i = 0; i < LEN; i++){
cout << *(ptA_int + i) << " ";
}
cout << endl;

for (i = 0; i < LEN; i++){
cout << *(ptA_char + i) << " ";
}
cout << endl;

return 0;
}



No comments:

Post a Comment