Archive | August, 2010

C training – Structure padding & alignment properties

In this section we will learn about structure padding and why is it needed.


When we are talking about structure or some kind of data structure, there are two important things to take into consideration DATA ALIGNMENT & PADDING. Though these two concepts are different but related.

Before knowing more about Structure padding, one has to understand how machine performs reading and writing operations on memory.Most of the machines are designed in such a way that , memory reading will be efficient if it reads x-sized data stored on a memory location where address%x == zero.

For example consider int size on a machine is 4 bytes, then if that int is stored on location 1002, which is not evenly divisible by 4. Then since that int variable was not aligned according to the machine requirements, so the memory reading performance will not be efficient.Though this machine requirement is not same for all machines. Some machines can read very well though data is not aligned properly. So this requirement of data alignment keeps on changing depending on machines.

Since C’s main aim is to support portable programs, so it should ensure that data should be aligned properly so that it executes on all machines with out much changes.

This is all about alignment of data. Now it is C’s duty to align all the data of a c program has to be aligned properly on memory.By default basic data types of C will be aligned properly on memory. But what about user defined data types like Structs ? Structure will contain different data types . Consider below example.

Struct stud{

char ch; //Assume the starting address as 1000

int i; // what will be the address of this variable then ?

}stud_temp;

In the above example ch is stored at 1000 th location. Variable “i” is supposed to be stored at the location 1001 speaking logically. But by storing in such a way we are committing 2 mistakes. One is we are making this program non portable and other is, it will cause unaligned access of memory since cpu expects int to be stored on some address which is evenly divisible by 4 (i.e 1004 th address in this eg). Such unaligned access will make some systems crash the program.

So the ideal data alignment for above example is 1000 and 1004th byte for ch and i accordingly. So it looks like ..

Struct stud{

char ch; //Assume the starting address as 1000

int i; // what will be the address of this variable then ? answer is ==> 1004

}stud_temp;

Now structure stud_temp instance variables are aligned properly so that it is portable and gives respect to machine architecture and aligns data accordingly .

But did you observe carefully ??? ch is char, it is supposed to take only 1 byte.. but what about 1001,1002,1003 locations ? is it allocated to ch or what happens to it ? Compiler is very intelligent to make those bytes as unused , which means it is just left empty to make alignment proper on memory. this is known as Padding.

This is the basic information about structure padding and alignment properties. I will follow up this post with more information on variety examples to make you understand more about structure padding and alignment and portability.

More later in following posts ..

Posted in C - Fresher questions, C Tutorials1 Comment

Best .net Training:When to use Interface and Abstract Class

When your you have family of related classed which are sharing some common functionality better use Abstract class. When you have classes which are not related and still you may need same methods and properties then the choice is Interfaces.Also when you have code which changes freequently better to use Abstract class which provides versioning.

Posted in C# FAQ1 Comment

Best .net training:Difference between Readonly and constant in C#

ReadOnly is a keyword in c# which is used like a constant .The only difference is you can have choice of intializing the value at runtime in a constructor, once you assign the value in readonly then it behaves like a constant. No way of changing its value later just like contstnt. A constant need to be intialised at the time of definition.So as per the discussion Constant is a compile time constant and readonly is runtime constant.

Posted in C# FAQ1 Comment

C training – some tricky declarations and some more tips

Lets discuss here about some tricky declarations.

==================================

1. What is the problem with this structure declaration

typedef struct {

char *item;

NODEPTR next;

} *NODEPTR;

A) problem here is typedef. A typedef creates new name for a type. But you can’t use until it

Is completely defined. So either you have to use it after its definition or other way round.

Consider below alternative ways of doing same.

A) typedef struct node {

char *item;

struct node *next;

} *NODEPTR;

OR

B) typedef struct node *NODEPTR;

struct node {

char *item;

NODEPTR next;

};

OR

C) struct node {

char *item;

struct node *next;

};

typedef struct node *NODEPTR;

2) What does this declaration mean ?

typedef int (*fptr)();

A) It defines a typedef,fptr – a function pointer which takes nothing and returns int.

3) What is difference in below 3 declarations.

Const char * cc1; ===> cc1 is a pointer to a constant charecter ( you can’t change value

pointed by cc1, but you can         change pointer value)

Char const * cc2; ===> cc2 is also a pointer to a constant charecter ( same as above )

char * const cc3; ===> cc3 is a constant pointer to a charecter.( you can change value

pointed by cc3, but you can’t        change pointer value)

4) Is void main() correct ?

A) No, it is not  correct according to ANSI standards. It may result in some wrong function

sequence.

5) Is char ch[5]=”hello” legal ?

A) Though it is supposed to be ch[6] for ‘\0′ termination of string, still above one is legal

as long as you wont use it for std string functions and other things which requires ‘\0′.

6) Can I implement abstract data type in C?

A) Of-course with the help of typedef.

Place a structure declaration in .c file, declare a typedef for that structure in “.h”

share “.h” with out side world, SO that they can never see what is declared inside that

struct but still they can be able to use it for instantiating and passing that struct variable

to all functions which requires struct variable of that kind.

Critics and inputs are welcome. Queries are also welcome.

Next section we will learn about structure padding.

Posted in C - Fresher questions, C Tutorials0 Comments

.Net Framework (Upcasting and Downcasting in C#)

Upcasting and down casting is especially usefull when you are dealing with Patterns , I mean design patterns in your real world programming.Inorder achieve polymorphic effect you actually need to implement base and derived classes. What i mean here is you have behaviour and that behaviour might change in future inorder to minimise the changes in your code you do inheritence. where ever inheritence is there you do upcasting and downcasting.see below example

  • Public abstract Class PatientContacts
  • {  //Define the common behaviou here and implement common logic like methods,properties etc.. }
  • Public Class RelativesContacts:PatientContacts
  • { //define the behaviour for to get the Relatives Contacts and implement specific logic  }
  • Public Class FriendsContacts :P atientContacts
  • { Define the behaviour to get the Friends contacts and implement specific logic for Friends contacts }
  • Public Class TestPolymorphism
  • { PatientContacts _rc=New RelativesContacts(); PatientContacts _fc=New FriendsContacts();}
  • This kind of polymorphism is espcially usefull when you are calling Relativecontacts and FriendsContacts in 100 classes by creating instances of them.so at any point of time if you want to remove FriendsContacts or RelativesContacts just think how much tedious it is to remove all those . so better way is to use Interfacse and use them polymorphicall to reduce number of changes.

Posted in C# FAQ3 Comments

Strings indepth in C#

Strings are immutable objects in C# i.e when you decale a string say string _cName=”Palle Technologies”;Now you try to manipulate the string by simply reassigning the name to : _cName=”Tech Palle”; When you try to access the  _cName you will alway get “Tech Palle” since the new string with _cName is again created . But the question here is what happens to old variable _cName ?. The answer is still old object stays in memory but now the variable _cName points to the new location where “Tech Palle” is stored and there is no way to retrieve the old string “Palle Technologies”.This is called immutability of strings.See sample “String Indepth sample in C#

Posted in C# FAQ6 Comments

Indexers in C#

  • Defining Indexers allows you to create classes that acts like virtual arrays
  • Indexers gives the possibilty of accessing objects with arry kind of syntax
  • Indexers created microsft just for syntactical convenience to create class,struct,interface that client application can access just like as an array.
  • Sample :
  • Public Class Employee
  • {
  •   public int this [int  year]
  • { get {double sal; //return employee salary for the given year from db; return sal;}
  • set { double sal; /*Call your own method to set salary based on year */sal=setsal(year);}
  • }

Posted in C# FAQ4 Comments

Arrays and Array list in C#

  • Array is fixed size and is a object
  • Array list is dynamic and can expand its size dynamically when ever the new elements added to arraylist.
  • We can say ArrayList is a resizable Array
  • At the time of declaration if you know the size of the list then use Array else ArrayList is best
  • But generally Arrays gives you higher performence since the size of the Array object is lesee compared to ArrayList
  • How to know the size of the array and arraylist when both are empty.
  • This is simple Just create an instance of array and arraylist say “a” and “al” are object of array and list.
  • type “a.” and “al.” in your visual studio then compare the number of properties and methods for arrays and ArrayLists.

Posted in C# FAQ5 Comments

Difference between Logical OR (|) and Conditional OR (||) in C#

Intro:  E1|E2. Even if E1 is false then also E2 is executed.

              E1||E2. E2 is always executed irrespective of E1’s result.

Posted in C# FAQ1 Comment

Logical And(&) and Conditional And (&&) in c#

There are different operators shipped with the c# language. But most confusing operators are bit-wise and (&),Conditional and(&&),

Bitwise-OR(|) and logical OR (||).In this article i will try to explain all these with a sample.

Bitwise and Conditional and: E1 && E2 –Expression 2 is evaluated only when Expression 1 is evaluated to true else E2 is not evaluated.But in E1&E2 E2 executes always irrespctive of the result of E1.

Sample :Public Class TestOpearators

{  static bool isEmployeeManager() {console.writeline(“Employee is not manager”);return false;}

static bool isEmployeeTechLead(){console.writeline(“Employee is a Tech Lead”);return true;}

public static void Main() { Console.WriteLine(“Bitwise AND:”);
      Console.WriteLine(“result is {0}”, isEmployeeManager()& isEmployeeTechLead());
      Console.WriteLine(“Logical AND:”);
      Console.WriteLine(“result is {0}”,isEmployeeManager()&& isEmployeeTechLead());

}

Program Result:

  • Bitwise AND:”)
  • Employee is not manager
  • Employee is a Tech Lead
  • result is False
  • Logical AND :
  • Employee is not manager
  • result is False

Posted in C# FAQ0 Comments