Integer occupies two bytes and character occupies one byte in memory. So when a integer pointer is incremented, it points two positions far from the present position. Supposing the starting address of the integer array is 4000, then after incrementation by one, the pointer points to 4002. Similarly for a character array if the starting address is 5001, then after incrementation the pointer points to 5002. This is dealt explicitly in the section on pointer arithmetic later in this chapter.
Exercise
What will be the output of the following program (taking help of the above example) ?
main ()
{
int alpha;
int *beta;
alpha = 1;
beta = α
printf ("\n Address of alpha = % u", &alpha);
printf ("\n Address of alpha = % u", beta);
printf ("\n Address of beta = % u", &beta);
printf ("\n Value of beta = % d", beta);
printf ("\n Value of alpha = % d", alpha);
printf On Value of alpha = % d", *(&alpha));
printf ("\n Value of alpha = % d",*beta);
}
Pointers and Arrays
As we have seen earlier that array is a popular data type among C programmers.
Pointers and arrays are so closely related that discussing pointers without I discussing arrays would make the discussion incomplete. All arrays make use I of pointers internally. Hence the need is to study them together rather than as I isolated topics.
C stores the elements of an array in contiguous memory locations.
Example:
main ()
{
int i;
int z [10];
for (i = 0; i < 10;z [i] = i, i++) i = 0; while (i < 5)
{
printf (" The address of element %d is %u\n", i, & z[i]);
printf ("and the value stored there is %d \n",*(&z[i]);
i++;
}
}
Output:
The address of element 0 is 4144 and the value stored there is 0 The address of element 1 is 4146 and the value stored there is 1 The address of element 2 is 4148 and the value stored there is 2 The address of element 3 is 4150 and the value stored there is 3 The address of element 4 is 4152 and the value stored there is 4.
We note here the following points about arrays and pointers:
• An array name is really a pointer to the first element in that array.
i.e. If z is a one dimensional array then the first element can be expressed as either & z [0] or simply as z. The second array element can be written as z [1] or (z+1) and so on. In general the address of the (i+1), th element can be expressed as either &z[i] or as (z+i).
So the above program could also be written as:
Example:-
main ()
int i;
i =0;
while (i <5)>Salient Features
Defining array arr explicitly calls for a fixed amount of storage (in this case 70 bytes) and creates an automatic pointer constant arr whose value is the same as the address of arr[0].
Defining pointer arr (as in char *arr) explicitly creates a pointer variable first. This pointer is then used to hold address of the string when the string is specified.
Besides assigning values during initialization, pointers can be reassigned, anywhere in the program as well:
arr = “Here it is!!"
An array can also be reassigned similarly.
Assignment of Pointers
Only pointers of the same type can be assigned to each other.
If p is an int pointer (int*p), then the only valid pointer assignments to p are
p = q where q is also int pointer
If you want to assign to p the value of a different type of pointer, then the cast operator can be used.
Example:
If pf is a pointer to anything other than integer then the following is also a valid assignment.
P = (int*) pf
This is similar to type casting in variables. Let's say if pf is a pointer to a character variable defined as char *pf and p is a pointer to an integer variable defined as int *p then the assignment p = pf is not valid. To overcome this we typecast the RHS into integer. Now the assignment p = (int *) pf is valid meaning p is an integer pointer pointing to same location as pf.
Example:
main ()
{
int a, b;
chare;
int *ip;
ip = &a;
*ip = 12;
ip = &b;
*ip = 50;
(char *) ip = &c;
*ip = 65;
Printf (“a = %d, b = %d, c = %c\n", a, b, c );
}
Output:
a = 12, b = 50, c = A
Pointer Arithmetic
Pointers do not have to point to single variables. They can also point at the cells of an array. For example, we can write
Int*ip;
Int a[10]
ip = &a [3];
and we would end up with ip pointing at the fourth cell of the array a (remember, arrays are 0-based, so a [o] is the first cell). We could illustrate the situation like this:
*ip gives us what ip points to, which in this case will be the value in a [3].
Once we have a pointer pointing into an array, we can start doing pointer arithmetic. Given that ip is a pointer to a [3], we can add 1 to ip:
ip + 1
What does it mean to add one to a pointer? In C, it gives a pointer to the cell one farther on, which in this case is a [4]. To make this clear, let's assign this new pointer to another pointer variable:
ip2 = ip + 1;
iP ip2
If we now do
*ip2 = 4;
we've set a[4] to 4. But it's not necessary to assign a new pointer value to a pointer variable in order to use it; we could also compute a new pointer value and use it immediately:
*(ip + 1) = 5;
In this last example, we've changed a[4] again, setting it to 5. The parentheses are needed because the unary " contents of operator * has higher precedence (i.e., binds more tightly than) the addition operator. If we wrote *ip + 1, without the parentheses, we'd be fetching the value pointed to by ip, and adding 1 to that value. The expression *(ip + 1), on the other hand, accesses the value one past the one pointed to by ip.
Given that we can add 1 to a pointer, it's not surprising that we can add and subtract other numbers as well. If ip still points to a[3], then
*('P + 3) = 7; sets a [6] to 7, and
*(ip - 2) = 4;
sets a[l] to 4.
Here we have added 1 to ip and assigned the new pointer to ip2, but there's no reason we can't add one to a pointer, and change the same pointer:
ip = ip + 1; Now ip points one past where it used to (to a[4], if we hadn't changed it in the meantime). We could also increment a pointer using
ip += 1; or
ip++;
Of course, pointers are not limited to ints. It's quite common to use pointers to other types, especially char. Here is an example of a function mystrcmp, which compares two strings, character by character using pointers.
Example:
char *p1 = &str1[0], *p2 = &str2[0];
while(1)
{
if(*p1 != *p2)
return *p1 - *p2;
if(*p1 == '\0' *p2 == '\0')
return 0; pl++; p2++;
}
The autoincrement operator ++ (like its companion, - -) makes it easy to do two things at once. The expression a[i + + ] accesses a[i] and simultaneously increments i, leaving it referencing the next cell of the array a. We can do the same thing with pointers: an expression like *ip++ lets us access what ip points to, while simultaneously incrementing ip so that it points to the next element. The preincrement form works, too: *++ip increments ip, then accesses what it points to. Similarly, we can use notations like *ip-- and *--ip.
As another example, here is the strcpy (string copy) loop using pointers:
char *dp = &dest [0], *sp = & src [0]; while(*sp != '\0')
*dp++ = *sp++; *dp = '\0';
One question that comes up is whether the expression *p++ increments p or what it points to. The answer is that it increments p. To increment what p points to, we can use (*p)++.
When you're doing pointer arithmetic, you have to remember how big the array the pointer points into is, so that you don't point outside it. If the array a has 10 elements, you can't access a[50] or a[-1] or even a[10] (remember, the valid subscripts for a 10-element array run from 0 to 9). Similarly, if a has 10 elements and ip points to a [3], you can't compute or access ip + 10 or ip - 5. (There is one special case: you can, in this case, compute, but not access, a pointer to the nonexistent element just beyond the end of the array, which in this case is &a[10]. This becomes useful when you're doing pointer comparisons, which we'll look at next.)
Pointer Subtraction and Comparison
We can add an integer to a pointer to get a new pointer, pointing somewhere beyond the original (as long as it's in the same array). For example, we might write
ip2 = ip1 + 3;
Applying a little algebra, we may ask the question if
ip2 - ip1 = 3
and the answer is, yes. When we subtract two pointers, as long as they point into the same array, the result is the number of elements separating them. We can also ask (again, as long as they point into the same array) whether one pointer is greater or less than another. The answer is one pointer is "greater than" another if it points beyond where the other one points. We can also compare pointers for equality and inequality. Two pointers are equal if they point to the same variable or to the same cell in an array, and are obviously unequal if they don't. Note that when testing for equality or inequality, the two pointers do not have to point into the same array.
One common use of pointer comparisons is when copying arrays using pointers. Here is a program segment which copies 10 elements from array to array2, using pointers. It uses an end pointer, ep, to keep track of when it should stop copying.
Example:
int array [10], array2[10];
int*ip1,*ip2 = &array2[0];
int*ep = &array1[10];
for(ip1 =&array1[0]; ip1
Example:
/*An example to illustrate the use of adding an integer to a integer pointer*/ main()
{
int num[] = (1,2,3,4);
int i = 0,*j;
j = &num[0]; /* this statement can also be written as j=num; */
while (i <4) address =" %u\n" element =" %d\n" color="#6633ff">Output:
address = 5001
element = 1
address = 5003
element = 2
address = 5005
element = 3
address = 5007
element = 4
Example:
An example to illustrate the use of adding an integer to a character pointer*/
main()
{
char arr[ ] = {a,b,c,d};
int i = 0; char *]; j = &arr[0]; while (i <4) address =" %u\n" element =" %d\n">Output:
address ~ 2000
element = a
address = 2001
element = b
address = 2002
element - c
address = 2003
element - d
Note :
In the first program we have collected the base address of the array in the variable j. When we are inside the loop for the first time j contains the address 5001 and the value at this address is 1. On incrementing j it points to the next memory location of its type (that is location at address 5003). But location number 5003 contains the second element of the array , therefore when the printf() statements are executed for the second time they print out the second element of the array and its address (i.e. 2 and 5003) and so on, till the last element of the array has been printed.
In the second program we have followed the same logic. The only difference is that j is now a character pointer. The base address of the array arr is 2000. Since a character occupies one byte in memory (an integer occupies two bytes) we see that on incrementing j the next memory address is 2001.
This is in contrast to the first program where on incrementing j the next memory address was 5003 and not 5002.
Below we give another example to illustrate adding/subtracting an integer to/from a pointer.
Example:
main()
{
char c() = "Beautiful";
printf ("\n %d", *(c+9)); }
Output:
0
Note:
In printf() we are actually trying to print out the contents of the 9 th address from the base address of the string. At this address there is a *\0' , which is automatically stored to mark the end of the string. The ascii value of '\0' is 0 which is what printed in the printf().
Exercises
What will be the output of the following programs?
1)
main()
{
Charc [10];
int i;
for (i=0;i<9;i++)*(c+i)=67; g="0;c[j];j++)" color="#ff0000">Answer to Selected Exercises
1) CCCCCCCCCC
2) e all work in CMC We all work in CMC
Comparing Two Pointers
Two pointers can be compared in a relational expression. However, this is possible only if both these variables are pointing to variable(s) of the same type. Consider that ptr_a and ptr_b are two pointer variables which point to data elements a and b.
ptr_a <> ptr_b Evaluates true provided a is stored after b
ptr_a <= ptr_b Evaluates true provided a is stored before b or ptr_a and ptr_b point to the same location ptr_a >= ptr_b Evaluates true provided a is stored after b or ptr_a and ptr_b point to the same location
ptr_a == ptr_b Evaluates true provided both pointers ptr__a and ptrb point to the same data element
ptr_a != ptr_b Evaluates true provided both pointers ptr_a and ptr_b point to different data elements but of the same type
ptr_a == NULL Evaluates true if ptr_a is assigned NULL value (zero)
Also, if ptr_begin and ptr_end point to members of the same array then,
ptr_end - ptr_begin
will give the difference in bytes between the storage location to which they point.
Pointers can be compared using the relational operators as follows:
Example:
main()
{
intxfl = {1,2,3};
int *p , *q;
p=&x[0]; /* the starting address of the array x() is stored in p */
q=&x[0]; /* the same address of the array x[] is also stored in q */
if(p==q)
{
printf ("%u\n%u ",p,q); /* prints the value stored in p and q
which are same in this case */
printf ("\nThe values of p and q are equal");
} else
{ P++;
q--;
printf ("%u\n%u ",p,q);
printf ("\n\nThe values of p and q are not equal");
} }
Output:
65520 65520 The values of p and q are equal
Note:
In this program we assumed the address of x[0] to be 65520 which is stored in both p and q.
Now let's say we change the program as follows:
main()
{
int x() = {1,2,3};
int *p, *q;
p=&x[0]; /* the starting address of the array xQ is stored in p 1
q=&x[1 j; /* a different address of the array xQ is stored in q */
printf ("%u\n%u\n ",p,q); /* prints the address of p and q before entering
the loop */ if(p==q)
{
printf ("%u\n%u ",p,q); /* prints the value stored in p and q after
entering the loop */ printf ("\nThe values of p and q are equal");
} else
{
{p++;q--};
printf ("%u\n%u ",p,q);
printf ("\n\nThe values of p and q are not equal");
}
}
Output: 65520 65522 65522 65520
The values of p and q are not equal
Note:
In this program the address of x[0] is 65520 which is stored in p and the address that is stored in q is 65522. So the two addresses that are stored in p and q are not same and the else part of the loop is executed. The value of p is incremented to 65522 from 65520 (integers are incremented by two bytes) and the value of q is decremented from 65522 to 65520 which are then printed.
Pointers and Functions
When we pass variables to a function as arguments, the value received by the function is a copy of the actual value. In the function, therefore, modification of the arguments (if any) is actually the modification to the copy of the variable received by the function. Hence, the same is not reflected in the calling program. This is known as function call by value.
This means that though the calling function can communicate with the called function by means of more than one argument, the communication from the called function to the calling function is only through a single returned value.
Example :
The following program attempts to change the values of a and b but does not give the desired result.
main()
{
int a = 5;
int b = 3;
printf (" Original value of a,b are %d%d\n",a,b);
interchange^,b);
printf(“new values of a,b are %d%d\n", a,b);
} interchange^,y) Strcpy (s, t)
char s [], tfj;
{While ((*s = *t) != '\0') {s++; t++; } } or strcpy(s.t) char s(), t();
{
While ((*s++ = *t++) != '\0'); }
Format:
The format for using this function is shown through the following example:
Example:
Main ()
{
Charstring1 = "Ronaldo";
charstring2 [10];
Strcpy (string1, string2);
Printf ("\n string1= %s", string1);
Printf ("\n string2= %s", string2);
}
Output: String1 = Ronaldo String2 = Ronaldo
On supplying the base address strcpy() goes on copying the characters in source string into the target string till it doesn't encounter the end of the source string ('\0').
st rem p
This function compares two strings: /* stremp: to compare two strings */ Strcmp (s.t) charsrj, t[];
{
int i; i = 0;
for( i=0; (s[i] == t[i]) && ( s[i] != '\0' t[i] != '\0'); i++); return (s[i] - t[i]); }
Format:
The format for using this function is shown through the following example:
Example:
main
{
char string 1[] = "Jerry";
char string2[] = "Ferry";
int i,j,k;
i = strcmp (string 1,"Jerry");
j = strcmp (string1,string2);
k = strcmp (string 1,"Jerry boy");
printf("\n%d%d%d",i,j,k);
}
Output:
0 4-32
In the first call to strcmp() the two strings are identical so it returned the value 0. In the second call the first character of "Jerry" doesn't match with the first character of "Ferry" and the result is 4 i.e. the first nonmatching characters in the strings and so on for the other string comparisons. The exact value of mismatch will rarely concern us.
Additional String Functions
If the scanf () function is used to get a string, all one gets is the first word of the string.
This is because scanf () reads a set of characters upto either a blank space or a new line character.
We can use another library function gets () to solve the above problem.
gets ()
gets() deals with strings as complete units. It is written using the getchar() function as follows.
Example:
#include
Main ()
{
char mes[100];
printf(“Enter a string : \n");
gets(mes);
printf("You had input this string : %s \n ",mes);
printf("Please enter another string : \n");
gets(mes);
printf("The string you entered now is : %s \n ",mes);
puts(mes); /*explained next*/
}
Output:
Enter a string:
Hello ! How are You
You had input this string : Hello ! How are You
Please enter another string Hello ! Fine Thank you
The string you entered now is : Hello ! Fine Thank you
Note:
gets() accepts input till the new line character '\n'. is entered
The '\n' is not stored, instead a NULL, '\0' is appended to the string.
puts() :
puts() is a function to output a string on terminal (VDU).
It automatically sends a new line escape sequence to the terminal after the string has been printed.
Hence, the puts() function is equivalent to
printf("%s\n",m);
where m is an array of characters.
Example:
main()
{
char cricketer[30];
puts(“Enter name");
gets(cricketer);
puts("Good cricket");
} Output:
Enter name
Sachin Tendulkar Good cricket
Note:
Unlike printf(), puts() can output only one string at a time.
Exercises
1) Write a program that accepts two integers and prints the cubes of the two integers. The program should have a function called cube() that takes an integer from main() and returns it's cube. The arguments to cube() should be passed through addresses.
2) Write the same program as in exercise 1 above, but now the arguments to cube() should be passed by value.
3) Assume str1, str2 and str3 are three string variables. Write a program to do the following:
a) Read two string constants into str1 and str2.
b) Compare to see if str1 and str2 are equal or not.
c) If they are not, join them together and store it in str1.
d) Then copy the contents of str1 to the variable str3.
e) At the end make the program print the contents of str1, str2, str3 andtheir lengths.
Answers to Selected Exercises
3) a)
# include
{
charstr1[20],str2[20];
printf(“Enter two strings\n");
scanf("%s %s",str1 ,str2);
printf("%s %s", str1, str2);
}
b)
# include
{
intj;
charstr1[20],str2[20]; printf(“Enter two strings\n"); scanf("%s %s",str1 ,str2);
j=strcmp(str1 ,str2);
if (]t=0)
printf("\n Strings are not equal"); else
printf("\n Strings are equal"); }
Command Line Arguments
A command line argument is a parameter supplied to a program when the program is invoked. This parameter may represent a filename that the program should process. For example, if we want to execute a program called 'progcp' to copy the contents of a file named fife 1 to another file2 , then we may use a command line like
progcp file 1 file2
where progcp is the filename where the executable code of the program is stored. The code progcp would copy filel to file2. The use of command line arguments eliminates the need to ask the user to enter the filenames during execution.
In 'C there is a way to pass command line arguments or parameters to a program so that when it begins executing, it can use the arguments as per the programs plan.
There are two parameters to be used by the programmer for this purpose while writing the code for the main() function.
argc ; An integer number equal to the number of positional parameters.
argv : An array of pointers, pointing to the strings passed as parameters. Let us see this through an example.
Example:
If the following program is written in a file myecho.c
#include
int argc;
char *argvfj;
{
int i; for(i=1;i
The following example is written in a file 'printstr.c'. It accepts two strings from the user and checks if they are same. If same it prints a message and if not it prints another message, using command line arguments.
Example:
main(argcargv) intargc, i;
char *argv();
{
i = strcmp(argv[1],argv[2]);
if(i==0)
printf(“The two strings are equal"); else
printf("The two strings are not equal"); }
When this program is compiled and the executable (lets say) is called printstr, then typing the following command from the Unix $ prompt:
$printstr string 1 string2
will give the output:
The two strings are not equal
Exercises
1. Write a program to accept 3 variables: one of type char, the next of type int and the third of type float. Print out the values and addresses of these three variables.
2. Write a function called swap(a, b) which interchanges two integers. Call this function from the sort() function whenever two integers have to be interchanged.
3. Write a function called max(a,b,c) that finds the bigger of two numbers a and b and stores it in the address of the int variable passed as the third argument.
4. Write a program to input a string and print it in reverse order.
Example: INPUT : INDIA
OUTPUT : AIDNI
5. Modify the above program to input a string and check if it is apalindrome.
(A string is a palindrome if it reads the same in the reverse order, e.g. "CMC", "MADAM" are palindromes.)
Answer to Selected Exercises
4)
# include
# include
# include
{
char ss()-'INDIA";
char *s;
s=ss+strlen(ss)-1;
while (s>=ss)
{
printf("%c",*s);
s—;
i /
}
No comments:
Post a Comment