Sunday, 12 June 2011

what is Structure in C? Different between Array and structure?Initializing Structures in C programming

Structures In C


A structure is a collection of one or more variables, possibly of different data types, grouped together under a single name for convenient handling. Is short structure in C programming can be defined as

  • A structure in C is a collection of items of different types. You can think of a structure as a "record" is in Pascal or a class in Java without methods.
  • Structures, or structs, are very useful in creating data structures larger and more complex than the ones we have discussed so far.
  • Simply you can group various built-in data types into a structure.
  • Object conepts was derived from Structure concept. You can achieve few object oriented goals using C structure but it is very complex.

Following is the example how to define a structure.

struct student {

char firstName[20];

char lastName[20];

char SSN[9];

float gpa;

};

Now you have a new datatype called student and you can use this datatype define your variables of student type:

struct student student_a, student_b;

or an array of students as

struct student students[50];

Another way to declare the same thing is:

struct {

char firstName[20];

char lastName[20];

char SSN[10];

float gpa;

} student_a, student_b;

All the variables inside an structure will be accessed using these values as student_a.firstNamewill give value of firstName variable. Similarly we can aqccess other variables.

Different between Array and structure

Array

Structure

i. Data Collection

Array is a collection of homogeneous data.

Structure is a collection of heterogeneous data.

ii. Element Reference

Array elements are referred by subscript.

Structure elements are referred by its unique name.

iii. Access Method

Array elements are accessed by it's position or subscript.

Stucture elements are accessed by its object as '.' operator.

iv. Data type

Array is a derived data type.

Structure is user defined data type.

v. Syntax

array_name[size];

struct struct_name
{
    structure element 1;
    structure element 2;
        ----------
        ----------
        structure element n;
}struct_var_nm;

vi. Example

int rno[5];

struct item_mst
{
    int rno;
    char nm[50];
}it;

Initializing Structures

An initializer for a structure is a brace-enclosed comma-separated list of values. An initializer is preceded by an equal sign (=). In the absence of designations, memory for structure members is allocated in the order declared, and memory address are assigned in increasing order, with the first component starting at the beginning address of the structure name itself. You do not have to initialize all members of a structure. The default initializer for a structure with static storage is the recursive default for each component; a structure with automatic storage has none.

The following subsection pertains to C only.

Named members of a structure can be initialized in any order; any named member of a union can be initialized, even if it is not the first member. A designator identifies the structure or union member to be initialized. The designator for a structure or union member consists of a dot and its identifier (.fieldname). A designator list is a combination of one or more designators for any of the aggregate types. A designation is a designator list followed by an equal sign (=).

A designator identifies a first subobject of the current object, which at the beginning of the initialization is the structure itself. After initializing the first subobject, the next subobject becomes the current object, and its first subobject is initialized; that is, initialization proceeds in forward order, and any previous subobject initializations are overridden.

The initializer for an automatic variable of a structure or any aggregate type can be a constant or non-constant expression. Allowing an initializer to be a constant or non-constant expression is ANSI C language feature.

The following declaration of a structure is a definition that contains designators, which remove some of the ambiguity about which subobject will be initialized by providing an explicit initialization. The following declaration defines an array with two element structures. In the excerpt below,[0].a and [1].a[0] are designator lists.

struct { int a[5], b; } game[] =

{ [0].a = { 1 }, [1].a[0] = 2 };

/* game[0].a[0] is 1, game[1].a[0] is 2, and all other elements are zero. */

The declaration syntax uses braces to indicate initializer lists, yet is referred to as a bracketed form. A fully bracketed form of a declaration is less likely to be misunderstood than a terser form. The following definition accomplishes the same thing, is legal and shorter, but inconsistently bracketed, and could be misleading. Neither b structure member of the two struct game objects is initialized to 2.

struct { int a[5], b; } game[] =

{ { 1 }, 2 };

/* game[0].a[0] is 1, game[1].a[0] is 2, and all other elements are zero. */

Unnamed structure or union members do not participate in initialization and have indeterminate value after initialization.

Example

The following definition shows a completely initialized structure:

struct address {

int street_no;

char *street_name;

char *city;

char *prov;

char *postal_code;

};

static struct address perm_address =

{ 3, "Savona Dr.", "Dundas", "Ontario", "L4B 2A1"};

How will you Describe the benefits of use pointer ? What are The Rules of Pointer Operation, a pretty assignment!!

Benefits of using Pointer :

C has a minimum number of fundamental data types - a single character, a single integer or float, and a few derived data types such as a structure, an enumerated list, and an array.

Pointers are special variables which store address of some other variables.

Syntax: datatype *ptr;
Here * indicates that ptr is a pointer variable which represents value stored at a particular address.

Example: int *p;
'p' is a pointer variable pointing to address location where an integer type is stored.

As with any variable, a pointer may be used on the right hand side of an assignment statement to assign its value to another pointer as shown in the following example.

// program to illustrate the basic use of pointers

#include

using namespace std;

void main()

{

// declares an integer variable and two pointers variables

int num = 10, *point_one, *point_two;

// assigns the address of variable num to pointer point_one

point_one = #

// assigns the (address) point_one to point_two

point_two = point_one;

cout<<"Pointers variables..."<

cout<<"*point_one = "<<*point_one<<"\n";

cout<<"*point_two = "<<*point_two<<"\n";

cout<<"\nNormal variable..."<

cout<<"num = "<

// displays value 10 stored in num since point_one

// and point_two now point to variable num

cout<<"\n-Both pointer point_one and"<<"\n";

cout<<"-point_two point to the same variable num."<<"\n";

cout<<"-That is why, they have same value, 10."<

}

Output:


The program example can be illustrated graphically as shown below. The memory address is arbitrarily chosen

Figure 8.6

Notice the difference between memory address and the actual data value, which stored at the memory address. Do not worry about the addresses, they are determined and provided by the system.

From the above example, we can:

1. Access the contents of a variable by using the variable name (num) and is called direct access.

2. Access the contents of a variable by using a pointer to the variable (*point_one or *point_two) and is called indirect access or indirection.

As a conclusion, if a pointer named pter of type int has been initialized to point to the variable named var, the following are true:

// declare a pointer variable named pter, where the

// data stored pointed to by pter is int type

int *pter;

// assign the address of variable named var to a pointer variable named pter

pter = &var;

*pter and var both refer to the contents of var (that is, whatever data value stored there).pter and &var refer to the address of var (the pter only hold the address of variable var not the actual data value).So, a pointer name without the indirection operator (*) accesses the pointer value itself, which is of course, the address of the variable pointed to. Very confused :o).

The main Benefits or advantages of using pointers are
1.) Function cannot return more than one value. But when the same function can modify many pointer variables and function as if it is returning more than one variable.
2.) In the case of arrays, we can decide the size of th array at runtime by allocating the necessary space.

3. Pointers allow us to pass values to functions using call by reference. This is useful when large sized arrays are passed as arguments to functions. A function can return more than one value by using call by reference.
4. Dynamic allocation of memory is possible with the help of pointers.
5. We can resize data structures. For instance, if an array's memory is fixed, it cannot be resized. But in case of an array whose memory is created out of malloc can be resized.
6. Pointers point to physical memory and allow quicker access to data.


The Rules of Pointer Operation

The following Rules apply when performing operation on pointer variables

· Always initialize pointer variables.

· A pointer variable can be assigned the Address of another variables.

· A pointer variable can be assigned the Address of pointer another variables.

· A pointer variable can be pre-fixed or post fixed with increament and decrement operator.

· An integer value may be added or subtracted from a pointer variables.

· When two pointer point to the same array , one pointer variable can be subtract from another.

· When two pointer point to the objects of the same data types, can be compared using relational operational operators.

· A pointer variable cannot be multiplied by a constant.

· Two pointer values cannot be added.

· A value cannot be assigned to an arbitrary address ( i.e &x= 10 is illegal)

· With strings, never forget to include the terminating '\0' when calculating the storage size.

· Check the return value of malloc() and make sure it's not NULL before using it then cast it to the desired type.

· For every malloc() there is an equal and opposite free()!

· Remember that &variable is a pointer.

· After freeing a pointer always set it to NULL.

For example.

int * pint=(int *)malloc(sizeof(int)) ;
/*
Do something with pint
*/
free(pint) ;
pint = NULL;

Setting pint to NULL is a safety feature. Just because the memory has been released by the call to free() does not prevent it accidentally being reused. This could lead to a nasty bug. Forcing it to NULL will show any "freed pointer reuse" bugs much sooner.

What is a Pointer ? how is a pointer initialized?, An assignment on C programming.

Point:

A pointers is a special type of variable which holds the address or location of another variable. Pointers point to these locations by keeping a record of the spot at which they were stored. Pointers to variables are found by recording the address at which a variable is stored. It is always possible to find the address of a piece of storage in C using the special & operator. For instance: if location were a float type variable, it would be easy to find a pointer to it called location_ptr.

float location;

float *location_ptr,*address;

location_ptr = &(location);

or

address = &(location);

The declarations of pointers look a little strange at first. The star * symbol which stands in front of the variable name is C's way of declaring that variable to be a pointer. The four lines above make two identical pointers to a floating point variable called location, one of them is called location_ptr and the other is called address. The point is that a pointer is just a place to keep a record of the address of a variable, so they are really the same thing.

A pointer is a bundle of information that has two parts. One part is the address of the beginning of the segment of memory that holds whatever is pointed to. The other part is the type of value that the pointer points to the beginning of. This tells the computer how much of the memory after the beginning to read and how to interpret it. Thus, if the pointer is of a type int, the segment of memory returned will be four bytes long (32 bits) and be interpreted as an integer. In the case of a function, the type is the type of value that the function will return, although the address is the address of the beginning of the function executable.

Initialization of POINTER in C:

Once a pointer is declared, the programmer must initialize the pointer, that is, make the pointer point to something. Don’t make it point to nothing; it is dangerous.Like regular variables, uninitialized pointers will not cause a compiler error, but using an uninitialized pointer could result in unpredictable and potentially disastrous outcomes.Until pointer holds an address of a variable, it isn’t useful.C uses two pointer operators:

1. Indirection operator (*) – has been explained previously.

2. Address-of-operator (&) – means return the address of.

When the & operator is placed before the name of a variable, the address-of-operator returns the memory address of the variable/operand.

For example:

#include

int main(void)

{

int *m;

int location = 200;

m = &location;

printf("The data, *m = %d\n",*m);

printf("The address where the data pointed to, m = %d\n", m);

return 0;

}

Output:

Therefore a pointer must be initialized with a statement that uses & operator as shown below:

// declare a pointer variable, m of type int

int *m;

// assign the address of variable location

// to variable m, so pointer m is pointing to variable location

m = &location;

// the actual data assigned to variable location

location = 200;

This statement means places the memory address of variable location into variable m. The memory address refers to the computer’s internal location where the actual data is stored. What and where the address is? It is determined by the system.In other word, pointer variable m receives the address of variable location or the memory address of the variable location is assigned to pointer variable m

.


Graphically it can be represented as shown below:


Let re-examine the indirection operator (*). Actually * is a complement of &. It means returns the value of the variable located at the address that follows.

From the previous example:

int *m;

m = &location;

location = 200;

q = *m;

The q = *m; statement will place the actual data value stored in variable location into variable q. That means q receives the actual data value stored at the memory address hold by variable m or the value stored in the variable location pointed to by variable m. Very confused huh?The * operator appears before a pointer variable in only two places:

1. When declaring a pointer variable.

2. When dereferencing a pointer variable (to find the data it points to).