K&R C Programs Exercise 5-7

Exercise 5-7. Rewrite readlines to store lines in an array supplied by main, rather than calling alloc to maintain storage itself. How much faster is the program? The K&R readlines from Section 5.6 calls a custom alloc to carve space out of a static buffer. This exercise moves storage to a flat char linestore[] array …

K&R C Programs Exercise 5-6

Exercise 5-6. Rewrite appropriate programs from earlier chapters and exercises with pointers instead of array indexing. Good possibilities include getline (Chapters 1 and 4), atoi, itoa, and their variants (Chapters 2, 3, 4), reverse (Chapter 3), strindex and getop (Chapter 4). This exercise is about translation: every array subscript a[i] can be written as *(a+i), …

K&R C Programs Exercise 5-5

Exercise 5-5. Write versions of the library functions strncpy, strncat, and strncmp, which operate on at most the first n characters of their argument strings. For example, strncpy(s,t,n) copies at most n characters of t to s. See the description in Appendix B. Three functions, each with a character count limit n. The non-obvious behaviour …

K&R C Programs Exercise 5-4

Exercise 5-4. Write the function strend(s,t), which returns 1 if the string t occurs at the end of the string s, and zero otherwise. Advance both pointers to their respective null terminators, then walk backwards together comparing characters. If t runs out first (pointer reaches the start of t), every character matched — t is …

K&R C Programs Exercise 5-3

Exercise 5-3. Write a pointer version of the function strcat that we showed in Chapter 2: strcat(s,t) copies the string t to the end of s. The Chapter 2 version used array indexing with integer subscripts. The pointer version eliminates the index variables entirely: advance s to its null terminator, then copy t character-by-character (including …

K&R C Programs Exercise 5-2

Exercise 5-2. Write getfloat, the floating-point analog of getint. What type does getfloat return as its function value? getfloat returns int — the same as getint. This might seem surprising since it reads a double. The return value is used as a status indicator: it returns the terminating non-numeric character (so the caller can check …