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.

References:

 

[Screenshots] Where’s My Money?

Logo_wide.scale-100

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:
screenshot_04262013_235733

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:

UserControlDesign

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.

CUC_Step_1

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

CUC_Step_1_1

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:

<UserControl
    x:Class="User_Control.CardControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:local="using:User_Control"
    xmlns:mc="http://schemas.openxmlformats..."
    d:DesignHeight="400"
    d:DesignWidth="600"
    mc:Ignorable="d">

</UserControl>

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”

<Grid
    Width="400"
    Height="150"
    Margin="5">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="150" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>

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

</Grid>

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

<Border
    Grid.ColumnSpan="2"
    Background="#FFECECEC"
    BorderBrush="#FFC8C8C8"
    BorderThickness="5,1,1,1" />

ControlBackgound

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

<Border
    Width="120"
    Height="120"
    Margin="5,0,0,0"
    BorderBrush="LightGray"
    BorderThickness="1">
    <Border
        BorderBrush="White"
        BorderThickness="1">

        <!-- Image Will be Here -->

    </Border>
</Border>

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

Step 4: Now we want to put the Image

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

lets talk about the image source and the binding later.

Now we made together this

ControlBackgoundWithImage

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.

<Grid
    Grid.Column="1"
    Margin="5,15,15,15">
    <Grid.RowDefinitions>
        <RowDefinition
            Height="30" />
        <RowDefinition Height="*" />
        <RowDefinition Height="25" />
    </Grid.RowDefinitions>

    <TextBlock
        Grid.Row="0"
        FontFamily="Segoe UI"
        FontSize="22"
        Foreground="#FF323232"
        Text="{Binding Title}" />

    <TextBlock
        Grid.Row="1"
        FontFamily="Segoe UI"
        FontSize="11"
        Foreground="#FF636363"
        Text="{Binding Content}"
        TextTrimming="WordEllipsis"
        TextWrapping="Wrap" />

    <HyperlinkButton
        Grid.Row="2"
        HorizontalAlignment="Right"
        VerticalAlignment="Center"
        Click="HyperClicked"
        Content="read more..."
        FontFamily="Segoe UI"
        FontSize="11"
        FontWeight="Light"
        Foreground="#FF1122CC"
        Padding="0" />
</Grid>

The result will be:

ControlFinal

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”.

CardDataClass

binding all this Properties will be as normal Like this:

<Image
    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
{
    get
    {
        return (string)GetValue(Card_ID_Property);
    }
    set
    {
        SetValue(Card_ID_Property, value);
    }
}

public static readonly DependencyProperty Card_ID_Property =
    DependencyProperty.Register(
        "ID",
        typeof(string),
        typeof(CardControl),
        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:

<GridView
    x:Name="UI_GView_Cards"
    ItemsSource="{Binding}"
    ScrollViewer.VerticalScrollBarVisibility="Hidden"
    SelectionMode="None">
    <GridView.ItemTemplate>
        <DataTemplate>
            <local:CardControl
                CardLinkPressed="CardControl_CardLinkPressed"
                ID="{Binding ID}"/>
        </DataTemplate>
    </GridView.ItemTemplate>
</GridView>

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)
{
    CardLinkPressed(GetValue(Card_ID_Property).ToString());
}

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;
            break;
        }
    }
}

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

screenshot_04262013_235757

———————————–

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

Load XML file [Windows Store]

Download source

Steps:

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

What?

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

Why?

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

How?

Create XML File: PROJECT >> Add New Item.

s1

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

s2

<?xml version="1.0" encoding="utf-8" ?>
<Flags>
 <Flag>
  <FlagImage>1.png</FlagImage>
  <FlagTitle>Flag of Ottoman Egypt</FlagTitle>
  <FlagDescription>(1793-1844)</FlagDescription>
 </Flag>
...
</Flags>

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

s3

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")
 select
 new Flag(item.Element("FlagImage").Value,
 item.Element("FlagTitle").Value,
 item.Element("FlagDescription").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:

<GridView
 x:Name="UIFlags"
 SelectionMode="None"
 ItemsSource="{Binding}"
 HorizontalAlignment="Center"
 VerticalAlignment="Center">

 <GridView.ItemTemplate>
 <DataTemplate>
 <StackPanel
 Margin="5"
 Orientation="Vertical"
 Background="#FF414141">
 <Image
 Source="{Binding FlagImage}"
 Width="200"
 Height="150"/>
 <TextBlock
 Text="{Binding FlagTitle}"
 Foreground="White"
 HorizontalAlignment="Center"/>
 <TextBlock
 Text="{Binding FlagDescription}"
 Foreground="White"
 HorizontalAlignment="Center"
 Margin="0,0,0,10"/>
 </StackPanel>
 </DataTemplate>
 </GridView.ItemTemplate>
</GridView>

Result:
screenshot_03132013_124104

Flags information collected from:
http://en.wikipedia.org/wiki/Flag_of_Egypt

Design Patterns [1/N] – Strategy Pattern

Problem:

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.

StrategyPatternUML


Chess Game

Download source – sourceforge

ChessGame

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”.
Notes:

  • 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].

GameMainClassDiagram

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.

ChessStrategyPatternClassDiagram

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:

image

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;

else

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;
int
startRow = oldRow,
startColumn = oldColumn,
endRow = newRow,
endColumn = newColumn,
numberOfUnits = 0;

while (startColumn != endColumn || startRow != endRow)
{
if (_board[startRow, startColumn] != null)
{
numberOfUnits++;
}
if (startRow > endRow)
startRow--;
if (startRow < endRow) startRow++; if (startColumn > endColumn)
startColumn--;
if (startColumn < endColumn)
startColumn++;
}
if (numberOfUnits == 1)
cleanPass = true;
else
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:

image

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.