Array Pointer [C++]

This post is for you if you know about arrays and pointers in C/C++ [check references for more info]

At first, we have to know the difference between:

  • Pointer to array.
  • Pointer to first element in array.

1. Pointer to first element in array.

It’s common to hear that “Array name is a pointer to that array“, but it is not correct, Array name yields a memory location, so it can be treated as a pointer, and the question is “Pointer to what?”

– It’s a pointer to the first element in that array, not pointer to the array itself.

Look at this:

int myArray[5];      // array of 5 integers

int *ptr1;           // pointer to integer

int *ptr2;           // pointer to integer

ptr1 = &myArray[0];  // ptr1 now is a pointer to the first element in "myArray"

ptr2 = myArray;      // ptr2 is also a pointer to the first element [prt1 equal ptr2]

And by using this way, you don’t have a pointer to the whole array, and that’s why you can’t get the length of array by using sizeof operator, and also can’t reallocate the array.

int myArray[5];                                 // array of 5 integers

int arraySize1 = sizeof(myArray) / sizeof(int); // arraySize1 will be equal 5

*ptr = myArray;                                 // pointer to first element

int arraySize2 = sizeof(ptr) / sizeof(int);     // arraySize2 will be equal 1

arraySize2 = 1 and that seems logical, as the size of a pointer to integer = 4 bytes. -Based on machine and OS-

2. Pointer to Array

This is how the pointer to array looks like:

int myArray[5];              // array of 5 integers.

int (*arrPtr)[5] = &myArray; // Pointer to the whole array.

And read as “arrPtr is pointer to array of 5 integers”

and now you can get the size of the array with using sizeof operator:

int myArray[5];                                // array of 5 integers.

int (*arrPtr)[5] = &myArray;                   // pointer to array

int arraySize = sizeof(*arrPtr) / sizeof(int); // arraySize will be equal 5

You may need to read this [Reading C type declarations] if you this confusing.



[Screenshots] Where’s My Money?


Now Available on the Store [Link]

Windows Store Application using C# and XAML

you will find all application screenshots in the slide show

Slide Show

This slideshow requires JavaScript.

Create User Control with customized events

Download source

In this post we will discuss:

  • How to make a user control.
  • Binding data.
  • Create an event handler

User controls are a kind of organization of the code, that helps you in reusing your code and also encapsulating some logic and user interface objects.


How to make a user control

User Controls are manly an UI elements, so the design is a main factor in making it.
Regardless of your experience or any programming limitations, start any designing tool and start working on the user experiences of your new control.
Out Target is to make Page like this:

Along this post I’ll talk and apply on a simple “Card” contains [Image – Title – Some text – read more link].
Using my Designing tool, i think this is what my new card control will looks like:


Now it’s coding time 😀

Start your Visual Studio 2012 and open your project or create new one.

Step 1.0: Add a new item “User Control”

right click on you project > add > New Item.


Step1.1: Select “User Control” and chose a appropriate name.


Now you new 2 files in you project, one for the design .xaml and another for logic and programming UI .xaml.cs

In .xaml file lets start applying the design initially it contains this few lines:



Step 2: we need to add an container that hold all our UI elements

with dimensions 400 * 150 and separated horizontally into 2 columns “Image and Text”

        <ColumnDefinition Width="150" />
        <ColumnDefinition Width="*" />

    <!-- Our XAML will be here -->


My control background is just a simple control with a background color and a border Like this

    BorderThickness="5,1,1,1" />


Step 3: Image framed within double borders, so we need two more borders in the first column “Image Column” with the size of the image


        <!-- Image Will be Here -->


Margins added to make the background spaces in the top, down and left equal

Step 4: Now we want to put the Image

    Source="{Binding ImagePath}"
    Stretch="None" />

lets talk about the image source and the binding later.

Now we made together this


Step 5: For the right column, I see we can separated it vertically into 3 rows
This is my implementation, another one may use a vertical instead, and the output will be almost the same.

1st row: with some Properties to fit the design.
2nd row: with some Properties to fit the design and limit the text length.
3rd row: with some Properties to fit the design.

            Height="30" />
        <RowDefinition Height="*" />
        <RowDefinition Height="25" />

        FontFamily="Segoe UI"
        Text="{Binding Title}" />

        FontFamily="Segoe UI"
        Text="{Binding Content}"
        TextWrapping="Wrap" />

        Content="read more..."
        FontFamily="Segoe UI"
        Padding="0" />

The result will be:


Binding data.

In order to use this “Card Control” we need to make its data dynamically filled, and the data binding will help in this point.

I’ll not discuss the data binding in this post, but I’ll tell you how to use it in your Control.

you need to create another class Holds one card data “CardData.cs” in my case it will contains this Properties:

  • ImagePath: hold image name and path in Assets
  • Title: Card Title
  • Content: Text content of card.
  • ID: card Number “Will be used later on event handling”.


binding all this Properties will be as normal Like this:

    Source="{Binding ImagePath}"
    Stretch="None" />

the different here is binding the “ID” we will use a specialized type of property called “Dependency properties”
In CardControl.xaml.cs

public string ID
        return (string)GetValue(Card_ID_Property);
        SetValue(Card_ID_Property, value);

public static readonly DependencyProperty Card_ID_Property =
        new PropertyMetadata(null));

Realted: Dependency Properties Overview

Using the User Control

In the Required page we will use the new “Card Control” Like this:

In .xaml file:

                ID="{Binding ID}"/>

In the MainPage.xaml.cs file:

create List of type “CardData”.
Assign it to the GridView ItemsSource.

private IEnumerable Cards;
//Fill Cards with Data.
UI_GView_Cards.ItemsSource = Cards;

Related: Load XML file

Create an event handler

now this is the last step.
To create an event handler you need to:

  • Define a delegate “describes the parameters that the event will pass”.
  • Use this delegate in event definition “describes the event name which will appear in the events list”
public delegate void HyperlinkEventHandler(string ID);
public event HyperlinkEventHandler CardLinkPressed;

all what i need to do is to call my new event every time the clicked

// HyperLinkButton Click Event
private void HyperClicked(object sender, RoutedEventArgs e)

and with a simple Logic, I can determine the action to be done every time the hyperLink clicked.

in MainPage.xaml.cs file:

private void CardControl_CardLinkPressed(string ID)
    foreach (CardData c in Cards)
        if (c.ID == ID)
            UI_TBlock_Title.Text = c.Title;
            UI_TBlock_Content.Text = c.Content;
            UI_Popup_Display.IsOpen = true;

In my testing application, it show the full card content in simple popup.



Don’t Forget to leave a comment,  and waiting for your opinions ☺

Load XML file [Windows Store]

Download source


  • Create / Load XML file.
  • Read XML file data.
  • Bind XML data with UI Control.


XML: stands for “Extensible Markup Language” based on “tags” and “name-value” pairs. [wiki]


you may need this technique to load some static data to your application in organized way.


Create XML File: PROJECT >> Add New Item.


Select meaningful name for the file, and start writing you data in suitable hierarchy.


<?xml version="1.0" encoding="utf-8" ?>
  <FlagTitle>Flag of Ottoman Egypt</FlagTitle>

now, lets read the XML file an create a list of Flags
First: create new class “Flags”


class Flag
 public string FlagImage { set; get; }
 public string FlagTitle { set; get; }
 public string FlagDescription { set; get; }</em>

 public Flag(string image, string title, string description)
  FlagImage = "ms-appx:///Assets/" + image;
  FlagTitle = title;
  FlagDescription = description;

Secound: Create list of the “Flags” in “MainPage.xaml.cs”

XDocument xmlDoc = XDocument.Load("Flags Of Egypt.xml");
IEnumerable<Flag> flags = from item in xmlDoc.Descendants("Flag")
 new Flag(item.Element("FlagImage").Value,

and finally bind this list with the UI element “Data Grid View”

UIFlags.ItemsSource = flags;

in the UI “MainPage.xaml”
the data grid view will looks like:


 Source="{Binding FlagImage}"
 Text="{Binding FlagTitle}"
 Text="{Binding FlagDescription}"


Flags information collected from:

Design Patterns [1/N] – Strategy Pattern


You have Classes agree in all its attributes but differ only in some behaviors.
Like in our Case the Chess Game, all the units differ only in the movement way.

Solution: Strategy Pattern

The best solution to such situations is to use the Strategy Pattern.
The idea is to define the Strategies “ways of movement” independent from the Classes “Chess units”, and make it interchangeable in order to be able to change the strategy in runtime.


Chess Game

Download source – sourceforge


It is a direct apply to the pattern on the chess game, if you are not familiar with its rules, you’ll find almost all what you need here.

In this example we don’t need to change the behavior in Runtime. “this point will be discussed at the end of the post under Changeable Behavior in Run-time”.

  • Not all functions implemented. [IsCheckmate – IsGameEnd]
  • Not all rules applied. [Castling – Promotion]

As shown in the screenshot, the UI consist of: the Board, Current Player Picture, History, and Exit and Reset buttons.
and the board is two picture boxes, One Holds the board background image, and the other I draw the game units on. – just for simplicity –

The Problem here is in the Chess units moving behavior, as each piece has its one legal moves differ from the other pieces.

The Code

Game main Classes:

  • Board Class.
  • Unit Class.
  • Some other classes inherited from Unit for each Game Unit [rook, knight, bishop, queen, king and pawns].


Applying the Strategy pattern to solve require adding a new interface “iMoveBehavior” contains one method called “IsLegalMove”, and create a class for each moving behavior that implement the “iMoveBehavior” interface methods.

and add an instance from Class implements “iMoveBehavior” interface inside the Unit Class, so we can set in runtime the moving behavior for each Unit, and able to invoke “IsLegalMove” from that instance.

iMoveBehavior Interface:

interface iMoveBehavior
    bool IsLegalMove(int oldRow, int oldColumn, int newRow, int newColumn, bool kill = true);

MoveEightDirections” Queen Movement:

class QueenMove:iMoveBehavior
public bool IsLegalMove(int oldRow, int oldColumn, int newRow, int newColumn, bool kill)
int vDiff = Math.Abs(oldRow - newRow);
int hDiff = Math.Abs(oldColumn - newColumn);

// Diagonal
if (hDiff == vDiff)
if (vDiff != 0)
return true;

// Horizontal
if (hDiff != 0 && vDiff == 0)
return true;

// Vertical
if (vDiff != 0 && hDiff == 0)
return true;

return false;

and so on for the other movements.


All Movement Strategy Classes.

As you see, I have to add some extra private fields and methods for the PawnMove Class, as it require that.

Using The Code

To make it easy on implementation, I give each piece a number called it “Type”

and this number also will determine if the piece either white or black one.

you can find Types Values in “Notes.txt”

Now, lets take a little about Board Class:


It holds a 2D array of “Units

private Unit[,] _board = new Unit[8, 8];

Some functions for check players units on the board:

//Check if the board in given row and column is null or not.

public bool IsEmptyCell(int row, int column);

//Check on the type of the unit in given row and column

public bool ExistWhiteUnit(int row, int column);

//Check on the type of the unit in given row and column

public bool ExistBlackUnit(int row, int column);

Function to get 2D array of integer that describe the distribution of the units on the board -for drawing-

public int[,] GetBoard()
int[,] types = new int[8, 8];

for (int r = 0; r < 8; r++)

for (int c = 0; c < 8; c++)

if (_board[r, c] == null)

types[r, c] = 0;


types[r, c] = _board[r, c].Type;
return types;

Move Function and couple of Not Implemented Functions*

public bool Move(int oldRow, int oldColumn, int newRow, int newColumn)
//Check if the "Start" and the "Destination" represent a legal movement.
bool kill = _board[newRow, newColumn] != null;
bool legalMove = _board[oldRow, oldColumn].Move(oldRow, oldColumn, newRow, newColumn, kill);

if (!legalMove)
return false;

//Checking that there is no other units on the pass between the "Start" and the "Destination".
//Note: Knights has the ability to jump over the other Chess Units, so I don't check on it
if (_board[oldRow, oldColumn] != null && _board[oldRow, oldColumn].Type%10 != 3)
bool cleanPass;
startRow = oldRow,
startColumn = oldColumn,
endRow = newRow,
endColumn = newColumn,
numberOfUnits = 0;

while (startColumn != endColumn || startRow != endRow)
if (_board[startRow, startColumn] != null)
if (startRow > endRow)
if (startRow < endRow) startRow++; if (startColumn > endColumn)
if (startColumn < endColumn)
if (numberOfUnits == 1)
cleanPass = true;
cleanPass = false;

if (!cleanPass)
return false;

//Move the Unit after checking that every thing is OK.
_board[newRow, newColumn] = _board[oldRow, oldColumn];
_board[oldRow, oldColumn] = null;
return true;
public bool IsGameEnd()
 throw new NotImplementedException();

public int IsCheckmate(int blackKingRow, int blackKingColumn, int whiteKingRow, int whiteKingColumn)
 throw  new NotImplementedException();

Unit Class:


the most important couple of lines in this Class are:

private iMoveBehavior _movingBehavior;

and inside the Move method:

bool legalMove = _movingBehavior.IsLegalMove(oldRow, oldColumn, newRow, newColumn, kill);

Don’t Forget to leave a comment,  and waiting for your opinions ☺

Design Patterns [0/N] – Intro

In this series, I’ll document what I read in Design Pattern, and I’ll attach a C# project as an example to illustrate the pattern idea and usage.

Why Design Patterns?

  • On my projects over last 2 years, I faced some problems which related some how with this topic.

What is the Design Patterns?

  • We resorted to Design patterns to solve some problems while Designing the projects, and a lot of wise people tried to put solutions for every problem till they found the most acceptable solutions, and now this solutions becomes Patterns that we can use.
  • To use this patterns you need to Read, Think and Apply.
    • Read the pattern -problem and solution-
    • Think how this problem is close to yours, and how this pattern can solve it.
    • Finally, Apply this solution on your application.

About the Title:

  • “Design Pattern” is our General topic name.
  • “[0/N]” is the topic number from N topics.
  • “- Intro” the sub-topic title like: [Intro, Observer Pattern, etc. ]

My references:

  • Mainly I read this book “Head First Design Patterns”.
  • “Google” For more info or explanations.

Three, Two, One, let’s Start.