


















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!



















(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.
In the program in Listing 4 four pointers are assigned the respective addresses of four
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);
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.
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.";
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
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 */
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") ;
Listing 8: Example to illustrate memory allocation for strings.
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-array [I may be altered, the pointer string-array cannot be assigned
string-array ++ ; /* {WRONG) d because string-array is a f i x e d address */
I 1 I
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
string-array is a pointh to the array of that name, sitting at a fixed address.
char * x = "We will always be the best."
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
a[] , a + i == & a [i]), the converse is also true. For any pointer p, the quantity
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
subscript i may be a positive or negative number! It is in this sense only that C allows
/* Program 7.9; File name: unit7-prog9. c */
Listing 9: Use of subscript operator.
/* Program 7. 9 : Output */ We are the b e s t.
deployed to print a string, its string argument may be replaced by a pointer to the string.
/* Program 7.10; File name: unit7-progl0.c */
scanf ("%s " , tree-2) ;
Here are some exercises for you.
characters arriving from the input, it ignores all leading white space character-blanks,
/* Program 7.11; File name: unit7-progll. c */
scanf("%d%c%dm,&x, &y, &z); (^) Pointers and Arrays
and suppose the input to this statement was:
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 ;
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
/* 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
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
/* Program 7.14; File name: unit7-progl4.c */
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! */
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
%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
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
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 */
C
printf("Type "I like C!, then values for x and y... " ) ;
printf("Thank you! The sum of x and y is: OM\n", x + y) ; e l s e
1
(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.
format conversion character which follows it, causes the comesponding input to be
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,
summarised below:
%o reads numbers in octal notation;
%x reads hex int s;
Akin to putchar() and getchar(), C provides in addition to p r i n t f ( ) and scanf() Pointers and Arrays
p u t s ( ) outputs its string argument on the terminal's screen:
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 h a t \ ' s i n c l u s i v e of t h e ,");
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
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
second, ... string in which the char lies, the second to its position in that string, the
This i s a two-dimensional array o f chars. It has 25 columns and 3 small rows.
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
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
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
pntr-aray [il[jl
pntr-array [i][j]! = '\0'