OpenVMS Source Code Demos

pointer_demo

//==============================================================================================================================
// title  : POINTER_DEMO.C
// author : Neil Rieck
// created: 2017-08-24
// purpose: demo the power of pointers
// ver who when     what
// --- --- -------- ------------------------------------------------------------------------------------------------------------
// 100 NSR 20170824 1. original code
//==============================================================================================================================
#include <stdio.h>								//
#include <stdlib.h>								//
//
//	here I will use an array of char in a very non-traditional way
//
char hack[127];
char	*ptr_c;						// pointer of bytes
short	*ptr_s;						// pointer of words
long	*ptr_l;						// pointer of longs
void	*ptr;						// this pointer has no flavor
//
main(){
	//
	//	initialize my data
	//
	for (int i=0; i<128; i++){
	    hack[i] = (char) i;				// populate array elements
	}
	//
	//	this block of code employs three pointers and...
	//	...only employs TYPE CASTING when we copy pointers
	//
	printf("-i-demos based upon flavored pointers\n");
	//
	ptr_c = &hack[0];				// copy the address
	printf("-i-address of hack[0]    : %p\n", ptr_c);
	for (int i=0; i<8; i++){
	    printf("-i-byte  values in hack[%d]: %02x\n",
		i,
		*(ptr_c+i)		);
	}
	ptr_s = (short*) ptr_c;				// copy the address
	for (int i=0; i<4; i++){
	    printf("-i-short values in hack[%d]: %04x\n",
		i,
		*(ptr_s+i)      	);
	}
	ptr_l = (long*) ptr_c;				// copy the address
	for (int i=0; i<2; i++){
	    printf("-i-long  values in hack[%d]: %08x\n",
		i,
		*(ptr_l+i)      	);
	}
	//--------------------------------------------------------------------
	//
	//	this block of code employs one pointer and...
	//	...only employs TYPE CASTING when we fetch the data
	//
	printf("-i-demos based upon one void pointer\n");
	//
	ptr = &hack[0];					// copy the address
	printf("-i-address of hack[0]    : %p\n", ptr);
	for (int i=0; i<8; i++){
	    printf("-i-byte  values in hack[%d]: %02x\n",
		i,
		*((char*)ptr+i)		);		// cast ptr to retrieve bytes
	}
	for (int i=0; i<4; i++){
	    printf("-i-short values in hack[%d]: %04x\n",
		i,
		*((short*)ptr+i)	);		// cast ptr to retrieve words
	}
	for (int i=0; i<2; i++){
	    printf("-i-long  values in hack[%d]: %08x\n",
		i,
		*((long*)ptr+i)		);		// cast ptr to retrieve longs
	}
}

Back to Home
Neil Rieck
Waterloo, Ontario, Canada.