Docsity

Pointers and Arrays in C Language, Study notes of C programming

Partial preview of the text

Download Pointers and Arrays in C Language and more Study notes C programming in PDF only on Docsity!

(ii) adding an integer to, or subtracting an integer from, a pointer; Pointers and Arrays

(iii) subtracting or comparing two pointers that point to elements of the same array; and

(iv) assigning or comparing a pointer to null.

A null pointer points nowhere.

In the program in Listing 4 four pointers are assigned the respective addresses of four

variables of the basic types. The output shows that adding I to each pointer increased it

by the width of the type it pointed at. /* Program 7.4; File name:unit7-prog4. c */ #include

char *char-pointer, char-variable; i n t *int-pointer, int-variable; f l o a t *float-pointer, float-variable; double *double-pointer, double-variable; char-pointer = &char-variable; int-pointer = &int-variable; float-pointer = &float-variable; double-pointer = &double-variable; printf("Address of char-variable: .%u, Address + 1: %u\nH, char-pointer, char-pointer + 1 ); printf("Address of int-variable: %u, Address + 1: %u\n", int-pointer, int-pointer + 1 ); printf("Address of float-variable: %u, Address + 1: %u\n", float-pointer, float-pointer + 1 ); printf("Address of double-variable: %u, Address + 1: %u\n", double-pointer, double-pointer + 1 ); printf("\nMoral: Adding 1 to a pointer does n?t necessarily\n"); printf("increase it by 1. Pointers are not ints.\nW);

return (0);

Listing 4: Effect on incrementation of pointers of different types.

Here is the output of Program 7.4 above on my computer. Very probably it will be different on yours.

/ * Program 7.4: Output */ Address of char-variable: 3220247843, Address + 1: 3220247844

Address of int-variable: 3220247832, Address + 1: 3220247836 Address of float-variable: 3220247824, Address + 1: 3220247828 Address of double-variable: 3220247808, Address + 1: 3220247816 Moral: Adding 1 to a pointer does not necessarily increase it by 1. Pointers are not ints.

Here are some exercises for you to try.

E l ) Create, compile and execute Program 7.1,7.2, 7.3 and 7.4.

Programming iri C Given the fact that a string is a pointer to itself, the definition:

char * fact = "We are still the best.";

makes sense. fact now points to the first byte of the string. But a subsequent assignment to fact : fact = "We will always be the best.";

will cause it to point to a different address of memory, the address where this new string

begins. It is important for you to realise that the declaration of fact allocates enough memory to hold not merely the pointer variable fact but also the entire length of the

string. The output of the program in Listing 8 should convince you of this truth. It prints

the addressof fact, and the addresses of each byte of the string to which it points. /* Program 7.8; F i l e name: uni t7-prog8. c */

**include

i n t main** ()

char * fact = "We will always be the best."; printf("Bytes allocated for fact: %d\nU, sizeof fact) ; printf("Memory address of fact: %u\nW, & fact); for (printf("String cntents: \n") ;

  • fact! = '\O'; fact ++) printf("\t\t%c is at %u\nn, * fact, fact); return (0);

Listing 8: Example to illustrate memory allocation for strings.

Contrast this with a string array, defined in classic C thus:

s t a t i c char string-array [ I = "An array of chars";

Here the address string-array is fixed when the program has been compiled and linked. The size of string-array [I is just big enough to hold each byte in the

string, including its invisible terminator. This means that though each element of

string-array [I may be altered, the pointer string-array cannot be assigned

any other value. So the incrementation:

string-array ++ ; /* {WRONG) d because string-array is a f i x e d address */

I 1 I

is taboo; compare this with:

fact ++; /* {ACCEPTABLE),

because f a c t is a pointer */

in Listing 5 on page 44 and Listing 6 on the previous page in which fact was declared

as a pointer to a string; but it could be assigned the address of any char.

string-array is a pointh to the array of that name, sitting at a fixed address.

To recapitulate the definition:

char * x = "We will always be the best."

defi~~esa pointer variable x, and allocates memory to store the string, as well as the

pointer to it. x is a variable. It may be given other values as the program executes, the

address of any other char. On the other hand, the definition:

s t a t i c char x[l = "We will always be the best";

defines an array at a fixed memory location. x is a constant pointer: it points to the zeroth element of x [ 1. A new assignment cannot be made to x. In as much as pointers

can be used interchangeably with arrays (because, for any array

a[] , a + i == & a [i]), the converse is also true. For any pointer p, the quantity

p [i] has a meaning. It is the value of the ith object from the one that p points to, of Pointers and Arrays

the same type. Regarded in this way the symbols I] constitute an operator called the subscript operator. This operator associates from left to right and has a priority as high as the parentheses operator. Now it is not quite necessary that the ith object from the

one referenced by p be "ahead of' or "before it" in memory: in other words, the

subscript i may be a positive or negative number! It is in this sense only that C allows

negative subscripts. Program 7.9 has an example of the subscript operator.

/* Program 7.9; File name: unit7-prog9. c */

# include

char *fact = "We are the best.";

tor (i = 0 ; fact[i] != '\O'; i++)

putchar(fact[i]);

return (0);

Listing 9: Use of subscript operator.

/* Program 7. 9 : Output */ We are the b e s t.

Given that strings are pointers, it must now be clear that wherever printf() is

deployed to print a string, its string argument may be replaced by a pointer to the string.

Conversely because strings are arrays, whenever scanf () reads a string, a character

array must be in place to hold the characters entered. Consider Program 7.10:

/* Program 7.10; File name: unit7-progl0.c */

char tree-l[20], tree-2[20], tree-3[20], tree-4[20];

printf("Name your favourite tree:");

scanf("%s", tree-1);

printf("Name another tree that you like:");

scanf ("%s " , tree-2) ;

printf("Namea third:");

scanf("%sW, tree-3);

printf("Name a fourth tree that you appreciate:");

scanf("%s", tree-4);

printf("These are your favourite trees: %s, %s, %s and %s\nl',

t r e e l , tree-2, tree-3, tree-4);

printf("You're a good person!! !\nW);

return (0);

Here are some exercises for you.

E3) Create, compile and execute Program 7.5 - 7.10.

FM) Give the output of the in Listing^^10 and^ Listing^ 1 1^ on the next page.

When scanf() (with the % format conversion character) examines the stream of

characters arriving from the input, it ignores all leading white space character-blanks,

tabs, newlines or formfeeds; so in Program 7.10 if you responded with:

/* Program 7.11; File name: unit7-progll. c */

# include

scanf("%d%c%dm,&x, &y, &z); (^) Pointers and Arrays

and suppose the input to this statement was:

the x would get the value 5, y the value 'm' and z the value 6 respectively. But if

instead the input was:

the value assigned to x would be 7, y would be assigned the char value ' '(SPACE), and z would retain its former value of 6. The reason for this behaviour is as follows: in reading an int with %d,scanf (1 ignores all leading white space charcter; when it receives the input 7 it assigns it to x. With the %cformat conversion charcter, each keystroke is significant. IF is typed next, that is the value that y gets. Then m 1s received; but the corresponding format specifier (%d)expects an int value. Now scanf () stops reading as soon as it encounters a character that is not valid for the type being read. The attempt to assign the value m to z fails. This is illustrated in Program 7.13, appended below, and a sample output: /* Program 7.13; File name: unit-7progl3.c */ #include int main() < int x , z ;

char y;

printf("Type i n t h e values 5m6 f o r x , y and z without spaces:");

scanf("%d%c%d", &x, &y, &z);

p r i n t f ( " x = %d, y = %c, z = %d\nU, x , y , z ) ; printf("Type i n t h e values 7M8f o r x , y and 2 : " ) ; scanf("%d%c%d", &x, &y, & z ) ;

1 1

return (0);

/* Program 7.13: Output */ Type i n the values 5m6 for x, y and z without space: x = S , y = m , z = 6 Type in the values7m8 for x , y and z: 7 m 8 N o w x = 7 , y = , z = 6

For clarity, we have underlined the user inputs. Programs 7.9 and 7.10 would have behaved somewhat differently if the **** character had been included inside the

control string, separating %cfrom the second %d:

scanf("%d%c %dm, &, &y, 812);

Then an arbitrary number of blanks are permitted in the input to separate the value entered for y from that for z. This is illustrated by the two calls to scanf() in Program 7.14. Note the difference in their control strings. Then note the difference in the

assignments they made (or could not make) to x , y and z.

/* Program 7.14; File name: unit7-progl4.c */

include < s t d i o. h >

int main () C int x , z ; 49

Programming in C char y; printf("Enter values for x, y and z , using spaces for separators\nW); printf("Remeber to enter a non-white space 1 character for y:^ "); scanf ("Yd%c %dln, &x, &y, &z); I! printf("x^ =^ %d,^ y^ =^ %c,^ z^ =^ %dln,^ X ,^ y ,^ 2); i

printf("\nEnter values for x, y and z, but this time\nH);

b%

printf("no spaces between values for x and y: "1;

!j

scanf("%d %c %dl1, &x, &y, &z) ; printf("x = %d, y = %, z = %d", x, y, z ) ; return (0);

/ * Program 7.14: Output / Enter values for x , y and z , using spaces for separators Remember t o enter a non-white space character for y: 34 b 45 x = 34, y = b, z = 45 Enter values for x, y and z , but t h i s time no spaces between values for x and y: 45 b 56 /We typed spaces! */

x = 4 5 , y = , z = 4 5

The last line of the output above shows that scanf() terminates reading the input stream as soon as it encounters therein a character invalid for the type listed (it was

given a ' b' when it expected a numeric value for z, and did not read the 56 meant for

it). For decimal ints valid characters are an optional sign, followed by the digits 0 - 9;

for octals the digits 0 - 7; and for hex the digits 0 - 9, a - f o r A - F. A filed width (e.g.

%4d, %6c, 9630, %2x, etc.) may be specified: reading stops as soon as the specified number of charcters has been read in, or, as we noted in the last example, a charcter is entered that does not match the type being read. When a field width is supplied with %c, it is assumed that the corresponding argument is a pointer to a character array, at least as big as the field width specified. See Program 7.20.

The second case in which white spaces in the input to a scanf() can be made

significant is through a bracketed string read, explained below.

We learnt from Program 7.10 that the %s specification reads a sequence of characters of which the first must be a non-white space character; and reading terminates as soon as a white space character is met with. The corresponding argument must be a character array, at least one byte bigger than the sequence of non-white space characters entered, to hold the terminating null character: scanf() automatically appends it when it's done reading. If a field width is specified, then no more characters than that width can be read in. Given this propensity of scanf() to stop reading a string as soon as it encounters a white space character inside it, how can string such as: "I am a string. "

be stored via scanf()? For this purpose one uses a bracketed string read, % [...I where the square brackets [I are used to enclose all characters which are permissible m the mput. If any character other than those listed within the brackets occurs in the input string, furtheireading is terminated. Reciprocally, one may specify within the brackets

those characters which, if found in the input, will cause further reading of the string to

Programming in C If there are non-format characters within the control string of a^ scanf(),^ they must^ be

matched in the input. For example, consider the scanf() we'd used in Program 5.16:

scanf("%d-%d-%d", &Day, M o n t h , &Year);

The hyphens in the control string are non-format character. Their presence implied that three ints were to read in, with their values to be separated by a single intervening hyphen. Using any other separators would have led to error. To execute Program 7. below correctly, you would have to admit that you like C! /* Program 7.17; F i l e name: unit7-progl7. c */

#include

i nt main ()

C

i n t x, y;

printf("Type "I like C!, then values for x and y... " ) ;

i f (scanf("1 like C! %d %d", &x, &y) == 2)

printf("Thank you! The sum of x and y is: OM\n", x + y) ; e l s e

printf("1 will not add those numbers for you!\nW);

return (0);

1

Program 7.17 uses another interesting property of sc-anf(), one we've seen before

(refer to Program 5.16): that it returns the number of items that it has successfully read. If this does not equal the number expected by the program, an error message can be output.

An asterisk(*) in the control string of a scanf(), placed between the % sign and the

format conversion character which follows it, causes the comesponding input to be

ignored. Consider the scanf():

scanf("%f %*f %fg', &x, & z ) ;

Suppose the input was:

12.34 45.46 78.

Then x and z would get the values 12.34 and 78.90 respectively.

The valid characters for an input of floats are an optionally signed sequence of decimal digits, followed by an optional decimal point and another sequence of decimal digits,

followed if need be by the letter e and E and an exponent, which may be signed. The

modifier 1 with the d or f specifiers is used to read in and assign longs and doubles

respectively. The modifier h with the d specifier reads short ints. These rules are

summarised below:

%d reads ints in decimal notation: argument must be a pointer to int;

%ld reads long intS": argument must be a pointer to long;

7ohd reads short ints: argument must be a pointer to short;

%u reads unsigned ints: argument must be a pointer to unsigned;

%o reads numbers in octal notation;

%lo reads long octal;

%ho reads short octals;

%x reads hex int s;

%lx reads long hex ints;

%hx reads short hex ints;

%e, %f and %g read numers expressed in floating point notation;

%le, %If, %lg require arguments to point to double;

%c reads single characters; argument is a pointer to char;

Akin to putchar() and getchar(), C provides in addition to p r i n t f ( ) and scanf() Pointers and Arrays

other functions for greater convenience of string U0. These are puts() and gets().

p u t s ( ) outputs its string argument on the terminal's screen:

p u t s ("This is an easy f u n c t i o n t o u s e , i s n \ ' t i t? " ) ;

Again, the argument of puts() may be the name of a string array. Consider the following program: /-; Program 7.18; File name: unit7-progl8.c */ #include < s t d i o. h >

s t a t i c char s t r i n g - 1 [ I = "I hope t h a t you enjoy C."; s t a t i c char string-2 [ I = "It's g r e a t fun!"; p u t s ( s t r i n g - 1 ) ;

Neither of the arrays string-:L[] or string-2[] ends with a newline; yet the output of the program is printed in two lines, with the cursor stationed on the third, as you can see by executing the program. The p u t s function replaces the terminating null character of its string argument by a newline.

gets() gets the characters that you type in at the keyboard, until is pressed. This bunch of characters is stored as a string array, for which memory must be allocated before gets() is invoked. In Program 7.19 below that array of 55 chars is get-stringl]. The indicating end of keyboard input is not stored in the array; gets() replaces it by a null character, marking the end of the input string. /* Program 7.19; File name: unit7-progl9.c */ #include < s t d i o. h> i n t main () C char g e t - s t r i n g [55];

p u t s ( " T e l l me how you a r e " ) ;

p u t s ( " i n 55 keystrokes o r less. ");

p u t s ( " T h a t \ ' s i n c l u s i v e of t h e ,");

p u t s ("which we expect you t o t y p e p r e s e n t l y! " ) ;

p r i n t f ( " % s " , "Begin here: "); g e t s ( g e t - s t r i n g ) ; p u t s ("Thanks f o r t h a t d e t a i l e d d e s c r i p t i o n. " ) ; return ( 0 ) ; 1

gets() does more than merely getting a string from the keyboard. If it was able to read the input string successfully, it returns the address of the array to which the string is

assigned; if not, or if no characters are read, it returns the null pointer, which by

convention has the value 0, and points nowhere.

E5) Describe what happens if you input more than 55 characters to Program 7.19.

E6) Give the output of the following program, in which a field width is specified with %c: /* Program 7.20; File name:unit7Lprog20.c */ #Include < s t d i o. h> i n t main () C char a r r a y [7]; l n t i ;

Pointers and Arrays

Programming in C (^) r e t u r n (0); 1

A string is a one-dimensional array: it has elements along a line. Any element can be

specified by a single subscript, which gives its position in the string. If you had a bunch

of strings, of equal length, each in a separate line, you would need two subscripts to

specify a particular character: the first would refer to the row, e.g. the zeroth, first,

second, ... string in which the char lies, the second to its position in that string, the

column number.

This i s a two-dimensional array o f chars. It has 25 columns and 3 small rows.

The picture we have so far presented is for string arrays unnecessarily restrictive,

because strings by their nature will be of arbitrary length. However, since strings are

pointers to char, it is possible to think of a bunch of several strings as a one

dimensional array of pointers. Consider the declaration:

s t a t i c c h a r * pntr-aray [I = C "This is the first string.", "This is the second string, a little longer.", "This is the third string.", "And this is the fourth and final string." 3 ;

First, what does this declaration mean? Is pntr-aray an array of pointers to char, or

is it a pointer to an array of chars? This may appear to be a confusing question but is

easily answered if you reason as follows: since the subscript operator, [I, has a higher precedence than the dereferencing operator. * (pntr-aray [I) is a char, pntr-aray [I is a pointer to char, and pntr-aray is an array of pointers to

char. Each element of it is a pointer to a string, because a string is a pointer to itself.

The declaration of pntr-aray[] reflects this: s t a t i c c h a r * pntr-aray [I =

p n t r l , pntr-2, pntr-3, pntr- 3 ;

where pntr-1, pntr-2, etc, are pointers to the first, second, etc. strings respectively. pntr-array [I is an array of four pointers. The program Listing 12 on the facing

page prints these strings: The outer loop of Program 7.22 runs over the four pointers;

the inner loop applies the subscript operator with j as subscript to extract the j t h

element of the i t h string. (Realise that as a loop condition the expression:

pntr-aray [il[jl

is equivalent to:

pntr-array [i][j]! = '\0'

The Inner loop is exited when the string terminator is sensed.)

Program 7.20 creates a ragged array, in which only as much space is allocated to store

the strings =is required for each separately (And for their pointers). If we had used a

two dimensional array to store these strings, the row dimension would have been at

least as great as to accommodate the largest string. That would have wasted valuable

memory when short strings had to be stored.

Consider now the declaration: