There was a need for a kind of variable that could store the address of another variable, so that the value of he variable could be directly accessed through its memory address and could be manipulated more easily and in a short span of time. The “pointer” is such a variable invented. It can be defined as a variable which stores the address of another variable. A pointer can be declared easily as shown below:
int *ptr1;
The “int” keyword is used to tell compiler that the pointer “ptr1” will store the memory address of an integer type variable. The symbol “*” called asterisk is used to tell the compiler that the variable “ptr1” is actually a pointer and that it will store the address of the variable it is pointing to irrespective of the bytes it will require to store the memory address. The pointer “ptr1” is said to point to an integer variable. N the above declaration we didn’t provide ptr1 with a value i.e., it’s empty now. If the declaration is made outside the function, the pointer “ptr1” will be initialized to a value that will not point to any of the variables or objects in a C program. Pointers initialized in this manner are said to have a null value or are called as “null” pointers. Null pointers are very useful in many of the C programs as they prevent system crash. A null pointer is implemented using a macro. The macro used is called “NULL” macro. If you set the value of a pointer using the above mentioned macro through an assignment statement as shown below:
Ptr1 = NULL;
It is assured that the pointer is now having a null value or it has become a null pointer. A null pointer can be tested using the below given statement
if (ptr 1== NULL);
Now suppose we want to store the address of an integer a in the above declared pointer “ptr1”, we will use the following statement:
ptr1 = &a;
Before proceeding further, we should now that a pointer has two values attached to it. One is the “l value” and the other one is the “r value”. L value is where the address of the variable pointed to is stored. R value stores the value of that variable. Now, the function of the “&” operator is to retrieve this l value of the variable a. the assignment operator copies the address of the variable a to the pointer “ptr1”. Now the pointer “ptr1” is said to point to variable “a”.
The “*” operator is also called the dereferencing operator and is used for de-referencing as follows:
*ptr 1 = 10;
The above statement will copy the value “10” to the address of variable a pointed to by the pointer “ptr1”. The above assignment statement can be written in another way as shown below:
Printf ( “ % d \n ”, *ptr1 );
The above statement will also print the value stored in the pointer on the screen as output.
Pointers are very much essential nowadays in programs. They solve basically two problems avoiding many other problems that may follow. First problem that they solve is that they make it easy to share information and data through and from the different sections of the memory. Secondly, they solve the problem of having complex structures. They make it easy to have linked data structures namely linked lists and queues and also binary trees. Pointers reduce the complexity of the program and there are many things that one can do using only pointers. Pointers are by no doubt a powerful C construct.
Thursday, October 6, 2011
Some details about Pointers in C...
Posted by
Sunflower
at
10/06/2011 06:17:00 PM
0
comments
Labels: C, C Language, Compiler, Complex, Complexity, Data, Functions, Memory, Objects, Pointers, Points, Programs, Storage, Structures, Values, Variables
![]() | Subscribe by Email |
|
Wednesday, October 5, 2011
Some details about Pointers to Arrays in C
A pointer is a variable that holds a memory address, usually of another variable in memory. The pointers are one of the most powerful and strongest features of C language. The correct understanding and use of pointers is critical to successful programming in C. pointer’s support C’s dynamic memory allocation routines. Pointers provide the means through which the memory location of a variable can be directly accessed and hence can be manipulated in the required way. Lastly, pointers can improve the efficiency of certain routines. Arrays and pointers are very loosely linked. C treats the name of array as if it were a pointer.
Consider the following code snippet:
Int *a ; // a is a pointer to an integer
Int age [10] ; //age is an array holding ten integers
For (int I = 0; I < 10 ; I ++)
a = age ; // makes a to point to the location where age points to. Age is a pointer pointing to age [0].
.
.
.
In the above code a is a pointer and age is an array holding 10 integers. The pointer a is made to point where age is pointing to. Since the name of an array is a pointer to its first element, the array name + 1 gives the address of the second element of the array, array name + 2 gives the address of the 3rd element, and so forth.
Pointers also may be arrayed like any other data type. To declare an array holding 10 integer pointers, the declaration would be as follows:
Int *ip [10] ; // array of 10 int pointers
After this declaration, contiguous memory would be allocated for 10 pointers that can point to integers. Now each of the pointers, the elements of pointer array, may be initialized. We can use the following statement:
Ip [3] = &a ;
To find the value of a, you can use the below given statement:
*ip [3] ;
The name of an array is actually a pointer to the first element of the array, the same holds true for the array of pointers also. Most often, an operation is carried on successive elements of an array. Using a loop for it and using the array elements indices. Consider the following code fragment that initializes an array to 0:
Const int abc = 20 ;
Int arr [ abc ] ;
For ( int I = 0 ; I < abc ; i++ )
Arr [ I ] = 0 ;
To execute the above code snippet, the compiler computes the address of array [ I ] every time by multiplying the index I by the size of an array element. That is, the compiler performs the multiplication for each element. A faster alternative would be to use a pointer as shown below:
Const int abc = 20 ;
Int arr [ abc ] ;
Int * arr2 ;
For ( arr2 = arr ; arr2 < &arr [ abc ] ; arr2++ )
*arr2 = 0;
Now the compiler only needs to evaluate a subscript once, when setting up the loop, and so saves 19 multiplication operations. So it is faster to use an element pointer than an index when you need to scan the arrays in a program. Pointers in c are defined by their data type and values. The data type determines the increment or decrements of the pointer value. The value is the address of the memory location to which the pointer is pointing. If you are using array notation, you don’t need to pass the dimensions.
Posted by
Sunflower
at
10/05/2011 07:45:00 PM
0
comments
Labels: Address, Arrays, C Language, Code, Data, Efficiency, Function, Integer, Memory, Pointers, Programming, Routines, Structures, Variables
![]() | Subscribe by Email |
|
Thursday, September 15, 2011
Some details about Pointers and Structures in C...
A pointer can be defined as a variable pointing to another variable or a variable storing the location or address of another variable.Pointers can be used to point to any data type.There are object pointers, function pointers, structure pointers and so on. Like any other pointers, structure pointers are also a very useful tool in C programming.Pointer structures are easy to declare and declared similarly like any other kind of pointer by putting a “*” sign before the name of the structure. See the example below:
Struct address *a1, *a2;
a1 = &b2;
a2 = &b3;
where b2 and b3 are the actual structure address variables. Using the below given assignment statement you can copy the details of structure pointed by a2 to a1:
*a1 = *a2;
Any member of a structure can be accessed using a pointer in the following way:
A->b
Here A is a pointer pointing to a structure and b is a data member or a member function of the structure being pointed. And there’s another way to access a member of a structure which has been given below:
(*A).b;
Both the statements are equivalent. Use of structure pointers is very common and useful.Be careful while dealing with structure pointers like any other normal pointer.The precedence of operators matters a lot. Be careful with the precedence of operators while programming in C.If we enclose *A is parentheses, an error will be generated and the code will not be compiled since the “.” Operator has got a high precedence than the”*” operator.Using so many parentheses can be quite a tedious job so, C allows us to use a shorthand notation to reduce the bombastic jargon. ” (*A).” can also be written as given below:
A ->
This is equivalent to (*A). but takes less characters. We can create pointers to structure arrays. A lot of space can be saved if we declare an array of pointers instead of an array to structures. In this only one structure is created and subsequently values are entered and disposed. Even structures can contain pointers as shown below:
Typedef struct
{
Char a[10];
Char *b;
} c;
c d;
char e[10];
gets(d.a,10);
d.b = (char *) malloc (sizeof (char[strlen(e)+ 1]));
strcpy(d.b, e);
This method is implemented when only a few records are required to be stored. When the size of the structure is large, it becomes difficult to pass and return the structures to the functions. To overcome this problem we can pass structure pointers to the functions. These structures can be accessed indirectly via pointers. Given below is a small code to illustrate the passing of structure pointers to the function and accessing them:
struct product
{
Int pno;
Float price;
};
Void inputpno (struct product *pnoptr);
Void outputpno (struct product *pnoptr);
Void main()
{
Struct product item;
Printf(“product details\n\n”);
Inputpno (&item);
Outputpno (&item);
}
Void outputpno (struct product *pnoptr)
{
Printf( “product no. = %d, price = %5.2f \n”, ( *pnoptr). Pno, (*pnoptr).price);
}
Void inputpno (struct product *pnoptr)
{
Int x;
Float y;
Struct product pno;
Printf( “product number: “);
Scanf( “%d”, &x);
( *pnoptr).pno = x;
Printf ( “price of the product: “);
Scanf( “%f”, &y);
( *pnoptr). Price = y;
}
In this program code, the prototypes, function calls and definitions have been changed in order to work with structure pointers. Dereferencing of a structure pointer is very common in programs. “->” (arrow) is an operator that is provided by C for accessing the member function of a structure. The 2 statements given below are equivalent:
Pnoptr -> pno;
(*pnoptr).pno;
Posted by
Sunflower
at
9/15/2011 08:44:00 PM
0
comments
Labels: Arrays, C, C Language, Code, Compilation, Definitions, Details, Functions, Input, Output, Pointers, Programming, Prototypes, Statements, Strings, Structures
![]() | Subscribe by Email |
|
Wednesday, September 14, 2011
Some details about pointers and strings in C...
There doesn’t exist anything in C like real strings. A string is an array. It can be defined as an array of characters. A string is terminated by a nul character “\0”. A string can be initialized normally as follows:
Char string[10];
String[0] = ‘c’;
String[1] = ‘a’;
String[2] = ‘t’;
String[3] = ‘s’;
Another way of initializing and declaring a string is as follows:
Char string[10] = “cats”;
The following statement asks compiler to allocate 10 bytes of memory for the string entered by the user. The string can store only 9 characters and the tenth one being used for “nul” character.
We can easily access strings and their constituent characters using character pointers. The string arrays are mostly used for storing char data type elements in the memory. The array of string pointers is preferred over two dimensional arrays of characters mainly for two reasons. The first reason is by implementing array of pointers, you can make more efficient use of available memory since it consumes lesser number of bytes for storing arrays of strings. The second main reason is that an array of string pointers makes the manipulation of strings easier. You can easily exchange the positions of strings in the array using pointers without touching their memory locations. This makes managing strings very convenient. Another way of initializing a string is by using pointers like
for example:
Char string[ ] = “cats”;
Char *a;
Here is a pointer pointing to the string “string”. Pointers are another suitable way to access string arrays and modify them as we want. Since strings are composed of characters, we should use pointers to characters. The types of the variable and the pointers must match otherwise an error will be generated. Be careful that you don’t use “&” (address of) operator to assign the address of a variable to the desired pointer. If you used it, the name of the array will be used as the address of that particular array. For this reason only we do not use “&” (address of) while passing a string to the function scanf(). For example see the following code:
Int a;
Char name[10];
Scanf(“%d%s”, &a, name);
The pointer allows us to access the required character in the string because we made it to point to that string. Functions can be passed to print labels and to call the function. Below is an example:
Void printlbl(char lbl[ ])
{
Printf (“the label: %s\n”, lbl);
}
int main()
{
char lbl2[] = "abc";
Printlbl(lbl2);
}
Now if we want to pass a pointer to the string array lbl2, we will use the following code:
Char *lblptr = lbl2;
The above declared pointer can be used in the function also like shown below:
Printlbl (lblptr) ;
After execution you will observe that both the statements give the same output. Now you will ask me why so? The answer for this is that when we pass an array as a parameter or an argument to a function, a pointer is automatically created without we knowing it and the arrays are passed by reference method automatically the way a pointer is passed. So the above written code can also be written the other way as follows:
void Printlbl(char *lbl)
{
printf("the Label: %s\n",lbl);
}
a code for dynamically allocated string is given below:
string = (char *)malloc(sizeof(char) * (len+1));
Some stings can be allocated dynamically. This is done when we don’t know how much long a string will go until the program is executed or when we don’t what size of string the user will enter.
Posted by
Sunflower
at
9/14/2011 09:01:00 PM
0
comments
Labels: Arrays, C Language, Characters, Code, Compiler, Data types, Declaration, Errors, Functions, Initialization, Memory, Pointers, program, software engineering, Strings, Variables
![]() | Subscribe by Email |
|
Tuesday, September 13, 2011
Some details about the types of pointers and arrays in C
Arrays are linear data structures whose data elements form a sequence. The elements of these linear structures are stored in memory as the contiguous memory locations and are represented as the same. These are the simplest data structures and are easy to be performed operations like insertion, deletion, searching, and traversal, sorting and merging. An array can store a finite number of data elements homogenous in nature i.e., they should be of same data type. The number of elements of the array represents the length or size of the array. The front and end index of the array are called lower bound and upper bound respectively. In C, the lower bound is always 0 and the upper bounds calculated as (size – 1). There are basically two types of arrays namely one dimensional arrays, two dimensional arrays and multi-dimensional arrays. The one –dimensional arrays are the simplest ones. Every name has a unique name. Each element of the array is represented by an index number or subscript of the element. An array is represented as:
Array name[ lower bound L, upper bound]
One - dimensional elements are implemented in C by allocating a sequence of contiguous memory location. The starting address of the first element of the array is called the “base address” of the array. C allows many searching algorithms namely linear search and binary search.
Two dimensional arrays are the arrays in which each element is itself an array. For example, a two dimensional array “A” can be represented as a table of M*N elements, where M is the number of rows and N is the number of columns. These arrays also like one dimensional array are stored as contiguous memory allocations. They must be linearized before storing.
These two dimensional arrays can be implemented in two ways i.e., row- major and column major. Row major implementation technique stores the arrays as rows whereas column major implementation technique stores arrays as columns i.e., it stores first row of the array as the first column in the memory. Algebraic Operations that can be performed on two- dimensional arrays are addition, subtraction, multiplication, division and transposition.
Pointer is a variable which stores the address of another variable. Pointers are the strongest as well as the weakest feature of the C programming language. Pointers are a mean to access and modify the address of a variable and its value. Pointers provide a way to implement dynamic allocation of memory and to improve the efficiency of program routines. But, they have a downside which is that they can cause your system to crash or hang if used in an incorrect way. There are no real arrays in a C program, but a chain of pointers. The name of the array is itself a pointer pointing to the first element of the array. There are many kinds of arrays. We will discuss them one by one. First is “array pointers”. These pointers store the address of the first element of the array. An array pointer can be declared as follows:
Int *a[10];
The second kind of pointers is “string arrays”. Strings as we know are nothing but just arrays of characters. A character pointer can be declared as:
Char name[ ]=”abc”;
Char *cpr;
The third type of pointer is called “const pointer” and can be defined as the constant pointer or a pointer to a constant. The fourth type of pointers is known as “structure pointers”. These pointers point to the structures. They too are declared by placing “*” in front of a structure name. Fifth type of pointer is called “object pointer” and points to an object the last and sixth type of pointer is the “THIS pointer” and it is used to automatically pass an implicit argument or a pointer to the object invoked in the function call.
Posted by
Ashish Agarwal
at
9/13/2011 11:18:00 PM
0
comments
Labels: Arrays, C Language, Engineering, Pointers, Software development, software engineering, String Arrays
![]() | Subscribe by Email |
|