Monday, April 18, 2011

C/C++ pointer exercise: Pointer Arithmetic

#include <iostream>

int main(int argc, char *argv[])
{
int var_int;
int *pt_int1 = &var_int;
int *pt_int2 = pt_int1 + 1;

int var_short;
int *pt_short1 = &var_short;
int *pt_short2 = pt_short1 + 1;

long var_long ;
long *pt_long1 = &var_long;
long *pt_long2 = pt_long1 + 1;

std::cout << "pt_int1 = " << pt_int1 << "\n";
std::cout << "pt_int2 = " << pt_int2 << "\n";
std::cout << "pt_int2 - pt_int1 = " << pt_int2 - pt_int1 << "\n";
std::cout << "(long)pt_int2 - (long)pt_int1 = " << (long)pt_int2 - (long)pt_int1 << "\n";
std::cout << "sizeof(int) = " << sizeof(int) << "\n";

std::cout << "\n";

std::cout << "pt_short1 = " << pt_short1 << "\n";
std::cout << "pt_short2 = " << pt_short2 << "\n";
std::cout << "pt_short2 - pt_short1 = " << pt_short2 - pt_short1 << "\n";
std::cout << "(long)pt_short2 - (long)pt_short1 = " << (long)pt_short2 - (long)pt_short1 << "\n";
std::cout << "sizeof(short) = " << sizeof(short) << "\n";

std::cout << "\n";

std::cout << "pt_long1 = " << pt_long1 << "\n";
std::cout << "pt_long2 = " << pt_long2 << "\n";
std::cout << "pt_long2 - pt_long1 = " << pt_long2 - pt_long1 << "\n";
std::cout << "(long)pt_long2 - (long)pt_long1 = " << (long)pt_long2 - (long)pt_long1 << "\n";
std::cout << "sizeof(long) = " << sizeof(long) << "\n";

std::cout << "\n";
}


c pointer exercise: Pointer Arithmetic