## Jan 30, 2012

### K & R C Programs Exercise 5-7.

K and R C, Solution to Exercise 5-7:
K and R C Programs Exercises provides the solution to all the exercises in the C Programming Language (2nd Edition). You can learn and solve K&R C Programs Exercise.
C Program to rewrite the readline function to store lines in the arraysupplied by main, rather than calling alloc to maintain storage. How much faster is the program?
The readlile function is slightly faster than the original version in the book K and R C Program page 109. Read more about C Programming Language .

```/***********************************************************
* You can use all the programs on  www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
*                      Happy Coding
***********************************************************/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>

#define TRUE     1
#define FALSE    0

#define MAXLINES 5000       /* maximum number of lines */
#define MAXLEN   1000       /* maximum length of a line */
char *lineptr[MAXLINES];
char lines[MAXLINES][MAXLEN];

int getline(char s[], int lim)
{
int c, i;

for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; i++)
s[i] = c;
if (c == '\n') {
s[i++] = c;
}
s[i] = '\0';
return i;
}

{
int len, nlines;
char *p, line[MAXLEN];

nlines = 0;
while ((len = getline(line, MAXLEN)) > 0)
if (nlines >= maxlines || (p = malloc(len)) == NULL)
return -1;
else {
line[len - 1] = '\0';  /* delete the newline */
strcpy(p, line);
lineptr[nlines++] = p;
}
return nlines;
}

{
int len, nlines;

nlines = 0;
while ((len = getline(lines[nlines], MAXLEN)) > 0)
if (nlines >= maxlines)
return -1;
else
lines[nlines++][len - 1] = '\0';
return nlines;
}

int main(int argc, char *argv[])
{

if (argc > 1 && *argv[1] == '2') {
} else {
}

return 0;
}

```
`Read more c programs `
```C Basic
C Strings
K and R C Programs Exercise```
You can easily select the code by double clicking on the code area above.

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!