Personal tools
Document Actions


by aullmj — last modified 2009-01-26 18:01

arrays and pointers demo code

Click here to get the file

Size 1.7 kB - File type text/x-c++src

File contents

//companion code for lecture on pointers and arrays
//Mark Aull, 2009

#include <iostream>
using namespace std;

//display function for any array
template <class asd> void arraydisplay(asd in[],int n){for (int ii=0;ii<n;cout <<in[ii]<<", ",ii++); cout <<endl;}

void main(int num,char *vals[])
	int ii,jj;
	int inta[10]={0,1,2,3,4,5,6,7,8,9};//make integer array
	int intb[10];
	for (ii=0;ii<10;intb[ii]=inta[ii]*inta[ii],ii++);//demo use of loop with array

	int *pa=inta;//make pointer, pointing to first element of inta
	cout <<endl<< inta<<' '<<pa<<endl;//display memory location indicated by pointer and array
	cout << inta[0]<<' '<<*pa<<endl;//index array and display memory at location of pointer
	cout << *inta<<' '<<pa[0]<<' '<<pa[5]<<endl;//demonstrate that pointer and arrays are exactly the same thing.

	int a=56;//make a regular integer
	pa=&a;//point pa at that memory location
	cout <<endl<<&pa<<endl<< &a <<' '<< pa<< endl<<a<<' '<<*pa<<' '<<pa[0]<<endl;//look at memory locations and values associated with this location
	cout << pa[1]<<endl;

	int **b;//double pointer
	cout <<endl<< b<<' '<<*b<<' '<<**b<<' '<<b[0][0]<<endl<<endl;

	int c2[3][3];//2D array
	for (ii=0;ii<3;ii++)
		for (jj=0;jj<3;jj++)
	for (jj=0;jj<3;jj++)
		for (ii=0;ii<3;cout<<&c2[2][ii]<<' ',ii++);//display memory locations of iith row elements
		for (ii=0;ii<3;cout<<c2[2][ii]<<' ',ii++);//display iith row elements
		cout <<endl;
	cout <<endl;

	for (ii=0;ii<num;cout<<ii<<": "<<vals[ii]<<endl,ii++);
	cout << vals[0][5]<<endl;
	cout << vals[num-1][1]<<endl;
	if (num==2)
		double d=atof(vals[1]);
		cout << d<<endl;
Related content