Search for notes by fellow students, in your own course and all over the country.

Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.

My Basket

You have nothing in your shopping cart yet.

Title: All about pointers and its interrelation with other things in C
Description: It contains info on pointers,related functions to it etc.. in C++ programming.It can be studied by 1st year beginner or anyone with decent computer knowledge.

Document Preview

Extracts from the notes are below, to see the PDF you'll receive please use the links above


8
...

(Global and static local pointers are automatically initialized to null
...
Null is used because C guarantees that no object will exist at the null address
...
One way to give a
pointer a null value is to assign zero to it
...
h> , define the macro NULL, which is a null
pointer constant
...
" For example, the
following sequence, although incorrect, will still be compiled without error:
int *p = 0;
*p = 10; /* wrong! */
In this case, the assignment through p causes an assignment at 0, which will usually cause a
program crash
...
A routine that accesses that array
knows that it has reached the end when it encounters the null value
...
4 The Pointer Operators
& is a unary operator that returns the memory address of its operand
...
You can think of & as
returning "the address of
...

q = *m;

places the value of count into q
...
5 Pointer Expressions
8
...
1 Pointer Assignments
You can use a pointer on the right-hand side of an assignment statement to assign its value to another
pointer
...
For example:
#include ...

Values at p1 and p2: 99 99
Addresses pointed to by p1 and p2: 0063FDF0 0063FDF0

Notice that the addresses are displayed by using the %p printf( ) format specifier, which causes printf( )
to display an address in the format used by the host computer
...
5
...

 There are two general categories of conversion: those that involve void * pointers, and those that
don't
...

o A void * pointer is called a generic pointer
...

o The void * type allows a function to specify a parameter that is capable of receiving any
type of pointer argument without reporting a type mismatch
...

 Without the void*
o Except for void *, all other pointer conversions must be performed by using an explicit
cast
...

o For example, consider the following program
#include ...
1, y;
int *p;
p = (int *) &x;
y = *p; /* attempt to assign y the value x through p */
printf(“The (incorrect) value of x is: %f”, y); /* The statement
won't output 100
...
*/
return 0;
}
OUTPUT: The (incorrect) value of x is: 1717986918
...

While it is technically permissible for a pointer to point to some other type of object, the pointer
will still ''think" that it is pointing to an object of its base type
...




One other pointer conversion is allowed: You can convert an integer into a pointer or a
pointer into an integer
...
(A cast is not needed
when converting zero, which is the null pointer
...
5
...

 let p1 be an integer pointer with a current value of 2000
...
After
the expression
p1++;



p1 contains 2004, not 2001
...

The same is true of decrements
...



All pointers will increase or decrease by the length of the data type they point to
...




You are not limited to the increment and decrement operators
...
The expression
p1 = p1 + 12;

makes p1 point to the 12th element of p1's type beyond the one it currently points to
...

i = &arr[1] ;
j = &arr[5] ;
printf ( "%d", j - i, ) ; // will print 4 not 16




All other arithmetic operations are prohibited
...


8
...
4 Pointer Comparisons
 You can compare two pointers in a relational expression
...


8
...
Consider this program fragment:
char str[80], *p1;
p1 = str;
Here, p1 has been set to the address of the first array element in str
...
)
An array name can be thought of as a constant pointer
...

Following example illustrate how you can use pointers in place of array indexing
...
*/
void putstr(char *s)
{

register int t;
for(t=0; s[t]; ++t)
putchar(s[t]);
}
/* Access s as a pointer
...
7 Pointers and 2D Arrays

/* Demo: 2-D array is an array of arrays */
void main( )
{
int s[4][2] = {
{ 1234, 56 },
{ 1212, 33 },
{ 1434, 80 },
{ 1312, 78 }
};
int i ;
for ( i = 0 ; i <= 3 ; i++ )
printf ( "\nAddress of %d th 1-D array = %u", i, s[i] ) ;
}

OUTPUT
Address of 0 th 1-D array = 65508
Address of 1 th 1-D array = 65516
Address of 2 th 1-D array = 65524
Address of 3 th 1-D array = 65532
The compiler knows that s is an array containing 4 one-dimensional arrays, each containing 2 integers
...

Suppose we want to refer to the element s[2][1] using pointers
...
Obviously ( 65524 + 1 ) Or ( s[2] + 1 ) would give the address 65528
...

We have already studied while learning one-dimensional arrays that num[i] is same as *( num + i )
...
Thus, all the following expressions refer to the same
element,
s[2][1]
* ( s[2] + 1 )
*(*(s+2)+1)
Using these concepts the following program prints out each element of a two-dimensional array using pointer
notation
...

1234 56
1212 33
1434 80
1312 78

Passing 2-D Array to a Function
There are three ways in which we can pass a 2-D array to a function
...

/* Three ways of accessing a 2-D array */
main( )
{
int a[3][4] = {
1, 2, 3, 4,
5, 6, 7, 8,
9, 0, 1, 6
};
clrscr( ) ;
display ( a, 3, 4 ) ;
show ( a, 3, 4 ) ;
print ( a, 3, 4 ) ;
}
display ( int *q, int row, int col )
{
int i, j ;
for ( i = 0 ; i < row ; i++ )
{
for ( j = 0 ; j < col ; j++ )
printf ( "%d ", * ( q + i * col + j ) ) ;
printf ( "\n" ) ;
}
printf ("\n" ) ;
}
show ( int ( *q )[4], int row, int col )

{
int i, j ;
int *p ;
for ( i = 0 ; i < row ; i++ )
{
p=q+i;
for ( j = 0 ; j < col ; j++ )
printf ( "%d ", * ( p + j ) ) ;
printf ( "\n" ) ;
}
printf ( "\n" ) ;
}
print ( int q[ ][4], int row, int col )
{
int i, j ;
for ( i = 0 ; i < row ; i++ )
{
for ( j = 0 ; j < col ; j++ )
printf ( "%d ", q[i][j] ) ;
printf ( "\n" ) ;
}
printf ( "\n" ) ;
}

And here is the output…
1234
5678
9016
1234
5678
9016
1234
5678
9016

In the display( ) function we have collected the base address of the 2-D array being passed to it in an ordinary
int pointer
...
Suppose i is equal to 2 and j is equal to 3, then we wish to reach the element
a[2][3]
...

The expression * ( q + i * col + j ) becomes * ( 65502 + 2 * 4 + 3)
...
Since
65502 is address of an integer, * ( 65502 + 11 ) turns out to be * (65546)
...
This is
indeed same as a[2][3]
...
* no
...
)
In the show( ) function we have defined q to be a pointer to an array of 4 integers through the declaration:
int ( *q )[4] ;
To begin with, q holds the base address of the zeroth 1-D array,

i
...
4001
...
Next time through the loop when i takes a value 1, the expression q + i fetches
the address of the first 1-D array
...
This address is once again assigned to p, and using it all elements of
the next 1-D array are accessed
...
The only advantage is that we can
now use the more familiar expression q[i][j] to access array elements
...
8 Arrays of Pointers



The declaration for an int pointer array of size 10 is
int *x[10];
To assign the address of an integer variable called var to the third element of the pointer array,
write
x[2] = &var;
To find the value of var, write
*x[2]



If you want to pass an array of pointers into a function, you can use the same method that you use
to pass other arrays: Simply call the function with the array name without any subscripts
...

Therefore you need to declare the parameter q as an array of integer pointers, as just shown
...
Pointer arrays are often
used to hold pointers to strings
...
This works because a string constant used in an
expression (in this case, an initialization) produces a pointer to the string
...
For
example, if num is passed a 2, the message Write Error is displayed
...


8
...

 Multiple indirection can be carried on to whatever extent desired, but more than a pointer to a
pointer is rarely needed
...
:
float **newbalance;

To access the target value indirectly pointed to by a pointer to a pointer, you must apply the asterisk
operator twice, as in this example:
#include ...

String Copying with Arrays and Pointers

8
...

Pass-By-Value
// Cube a variable using pass-by-value
...
h>
int cubeByValue( int number );
// prototype
int main( void )
{
int number = 5;
// initialize number
printf( "The original value of number is %d", number );
int temp = cubeByValue( number );
// pass number by value to
cubeByValue
printf( "\nThe new value of number is %d\n", number );
number = cubeByValue( number );
// pass number by value to
cubeByValue
printf( "\nThe new value of number is %d\n", number );
}
int cubeByValue( int number)
// calculate and return cube of integer argument
{
number=number*number*number;
return number;
// cube local variable n and return result
}
OUTPUT:
The original value of number is 5
The new value of number is 5
The new value of number is 125
Pass-By-Reference
passes the variable number by reference

#include ...
h>
int main ()
{
int a = 100, b = 200;
printf("Before swap, value of a and b are: %d and %d\n", a,b );
swap_value(a, b);
printf("After swap_value, value of a and b are: %d and %d\n", a,b );
swap_ref(&a,&b);
printf("After swap_ref, value of a and b are: %d and %d\n", a,b );
return 0;
}
void swap_value(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
printf("Inside swap_value, value of x and y are: %d and %d\n", a,b );
}
void swap_ref(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
printf("Inside swap_ref, value of a and b are: %d and %d\n", *a,*b );
}

8
...
This address is the
entry point of the function and it is the address used when the function is called
...

Function pointers also allow functions to be passed as arguments to other functions
...

#include ...
h>
void check(char *a, char *b, int (*cmp)(const char *, const char *));
int main(void)
{
char s1[80], s2[80];
int (*p)(const char *, const char *); /* function pointer */
p = strcmp; /* assign address of strcmp to p */

printf("Enter two strings
...
\n");
if(!(*cmp)(a, b))
printf("Equal");
else
printf("Not Equal");
}

Let's look closely at this program
...
It is shown here:
int (*p)(const char *, const char *);
This declaration tells the compiler that p is a pointer to a function that has two const char * parameters,
and returns an int result
...

Inside check( ), the expression
(*cmp)(a, b)
calls strcmp( ), which is pointed to by cmp, with the arguments a and b
...
This is one way to call a function through a pointer
...

cmp(a, b);
The reason that you will frequently see the first style is that it tips off anyone reading your code that a
function is being called through a
...
For
example, when an interpreter is written, the parser (the part that processes expressions) often calls various
support functions, such as those that compute mathematical operations (sine, cosine, tangent, etc
...
Instead of having a large switch statement with all of these
functions listed in it, an array of function pointers can be created
...

You can get a better idea of the value of function pointers by studying the expanded version of the
previous example, shown next
...
When checking
for numeric equality, the string ''0123" will compare equal to "123", even though the strings, themselves,
differ
...
h>
#include ...
h>
#include ...
\n");
gets (s1);
gets(s2);
if(isdigit(*sl)) {
printf(''Testing values for equality
...
\n");
check(s1, s2, strcmp);
}
return 0;
}
void check(char *a, char *b,int (*cmp)(const char *, const char
*))
{
if(!(*cmp)(a, b))
printf("Equal");
else
printf("Not Equal");
}
int compvalues(const char *a, const char *b)
{
if(atoi(a)==atoi(b))
return 0;
else
return 1;
}
In this program, if you enter a string that begins with a digit, compvalues( ) is passed to check( )
...
Since check( ) calls the function that it is passed, it can use a different
comparison function in different cases
...

Test
Test
Testing strings for equality
...
12 Dynamic memory allocation:
Memory layout of c program

malloc():
In dynamic memory allocation region of memory is allocated from the heap
...

The code fragment shown here allocates 1,000 bytes of contiguous memory:
char *p;
p = malloc(1000); /* get 1000 bytes */
After the assignment, p points to the first of 1,000 bytes of free memory
...
As
explained, a void * pointer is automatically converted to the type of the pointer on the left side of an
assignment
...
)
The next example allocates space for 50 integers
...

int *p;
p = malloc(50*sizeof(int));
Since the heap is not infinite, whenever you allocate memory, you must check the value returned by
malloc( ) to make sure that it is not null before using the pointer
...
The proper way to allocate memory and test for a valid pointer is illustrated
in this code fragment:
p = malloc(100);
if(!p) {
printf(''Out of memory
...
Just make sure
that you do not use the pointer p if it is null
...
Once the memory has been freed, it may be reused by a subsequent call to malloc( )
...
It is critical that you never
call free( ) with an invalid argument; this will damage the allocation system
...
Several examples of these are included in
Part Four
...

Dynamically Allocated Arrays
Sometimes you will want to allocate memory using malloc( ), but operate on that memory as if it were an
array, using array indexing
...
Since any
pointer can be indexed as if it were an array, this presents no trouble
...

/* Allocate space for a string dynamically, request user
input, and then print the string backwards
...
h>
#include ...
h>
int main(void)
{
char *s;
register int t;
s = malloc(80);
if(!s) {
printf(''Memory request failed
...
This is absolutely necessary to prevent accidental use of a
null pointer
...


You can also dynamically allocate multidimensional arrays
...
To see how this works, study the following example, which
builds a table of the numbers 1 through 10 raised to their first, second, third, and fourth powers
...
h>
#include ...
*/
int (*p)[10];
register int i, j;
/* allocate memory to hold a 4 x 10 array */
p = malloc(40*sizeof(int));
if(!p) {
printf(''Memory request failed
...
*/
pwr(int a, int b)
{
register int t=l;
for(; b; b--) t = t*a;
return t;
}
The output produced by this program is shown here
...
This declaration states that p is a pointer to an array of 10
integers
...
When p is incremented, it will point to the start of the
next 10 integers; when decremented, p will point to the previous 10 integers
...
This means that p can be indexed as a twodimensional array, as the program shows
...

One final point: As has been mentioned, in C++ you must cast all pointer conversions
...

restrict-Qualified Pointers
The C99 standard has added a new type qualifier that applies only to pointers: restrict
...
A pointer qualified
by restrict is initially the only means by which the object it points to is accessed
...
Thus, access to the object is
restricted to expressions based on the restrict-qualified pointer
...
By qualifying a
pointer with restrict, the compiler is better able to optimize certain types of routines
...
The restrict qualifier does not change the
semantics of a program
...
They give you
tremendous power, but when a pointer is used incorrectly, or contains the wrong value, it can be a very
difficult bug to find
...
The trouble
starts when you access an object through that pointer
...
If you read from it, you will get a garbage
value, which will probably cause your program to malfunction
...
In either case, the problem might not show up until later in the
execution of your program and may lead you to look for the bug in the wrong place
...
Programmers lose sleep
over this type of bug time and time again
...
To
help you avoid them, a few of the more common errors are discussed here
...
Consider this program:
/* This program is wrong
...
Here is why
...
This
causes the value of x to be written to some unknown memory location
...
However, as your program grows, the probability
increases of p pointing to something vital
...
In this simple
example, most compilers will issue a warning message stating that you are attempting to use an
uninitialized pointer, but the same type of error can occur in more roundabout ways that the compiler
can't detect
...
Consider the
following:
/* This program is wrong
...
h>
int main(void)
{
int x, *p;
x = 10;
p = x;
printf("%d", *p);
return 0;
}
The call to printf( ) does not print the value of x, which is 10, on the screen
...
That statement assigns the value 10 to the pointer p
...
To correct the program, write
p = &x;
As with the earlier error, most compilers will issue at least a warning message when you attempt to
assign x to p
...

Another error that sometimes occurs is caused by incorrect assumptions about the placement of variables
in memory
...
For these
reasons, making any comparisons between pointers that do not point to a common object may yield
unexpected results
...

is generally an invalid concept
...
But this would be rare
...
For example:

int first[10], second[10];
int *p, t;
p = first;
for(t=0; t<20; ++t) *p++ = t;
This is not a good way to initialize the arrays first and second with the numbers 0 through 19
...
This may not always be the case
...
See if you can find it
...
*/
#include ...
h>
int main(void)
{
char *p1;
char s[80];
p1 = s;
do {
gets(s); /* read a string */
/* print the decimal equivalent of each
character */
while(*p1)
printf('' %d", *p1++);
} while(strcmp(s, "done"));
return 0;
}
This program uses p1 to print the ASCII values associated with the characters contained in s
...
The first time through the
loop, p1 points to the first character in s
...
This next character may be part of the second string, another
variable, or a piece of the program! The proper way to write this program is
/* This program is now correct
...
h>
#include ...
In general, you should remember to
reinitialize a pointer if it is to be reused
...
Just be careful, and make sure that you know where each pointer is
pointing before you use it
Title: All about pointers and its interrelation with other things in C
Description: It contains info on pointers,related functions to it etc.. in C++ programming.It can be studied by 1st year beginner or anyone with decent computer knowledge.