20-CS-122-001 Computer Science II Spring 2012
Simple struct Array and Pointers

Virtual functions, classes, inheritance, lists, queues, stacks, applications

Prev      Next      Lectures      Source

#include <iostream>
#include <stdlib.h>
using namespace std;

typedef struct { int x; int y; int z; } Simple;

int main () {
   // Create objects s[0], s[1], s[2], s[3]
   Simple s[4] = { 1,2,3, 3,4,1, 8,1,8, 2,6,5 };
   Simple *simple_ptr = &s[2];

   cout << "The size of Simple is " << sizeof(Simple) << " bytes\n";
   cout << "The size of ptr to Simple is " << sizeof(simple_ptr) << " bytes\n";
   cout << "The size of Simple is " << sizeof(*simple_ptr) << " bytes\n";
   cout << "The size of array s is " << sizeof(s) << " bytes\n";
   cout << "=====================\n";

   cout << "The element s[2] is:\n";
   cout << s[2].x << " " << s[2].y << " "  << s[2].z << "\n";
   cout << "=====================\n";

   cout << "The element simple_ptr points to is:\n";
   cout << (*simple_ptr).x << " " << (*simple_ptr).y << " " 
	<< (*simple_ptr).z << "\n";
   cout << "=====================\n";

   cout << "The element simple_ptr points to is:\n";
   cout << simple_ptr->x << " " << simple_ptr->y << " " 
	<< simple_ptr->z << "\n";
   cout << "=====================\n";

   cout << "All the elements together are:\n";
   for (int i=0 ; i < 4 ; i++)
      cout << s[i].x << " " << s[i].y << " " << s[i].z << "\n";
   cout << "=====================\n";
}

// Sample output:
//  The size of Simple is 12 bytes
//  The size of ptr to Simple is 4 bytes
//  The size of Simple is 12 bytes
//  The size of array s is 48 bytes
//  =====================
//  The element s[2] is:
//  8 1 8
//  =====================
//  The element simple_ptr points to is:
//  8 1 8
//  =====================
//  The element simple_ptr points to is:
//  8 1 8
//  =====================
//  All the elements together are:
//  1 2 3
//  3 4 1
//  8 1 8
//  2 6 5
//  =====================