The K&R C standard library
last modified December 5, 2026 K&R C 1978
The C language has no built-in functions. Everything a program does
beyond computing, from printing to taking the square root, it does by
calling functions from a library. On UNIX the main library is
libc, which the compiler links to every program, and the
mathematical functions are in a separate library, libm. The
earlier articles have covered formatted
output, formatted input,
files, and the
string and character functions. This article
shows the other common functions.
Converting strings to numbers
atoi converts a string of decimal digits to an
int, atol to a long, and
atof converts a string to a double. All of them
skip leading white space, accept a sign, and stop at the first character
that does not belong to the number.
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("%d\n", atoi("1978"));
printf("%d\n", atoi(" -42 apples"));
printf("%d\n", atoi("apples"));
printf("%d\n", atoi("40000"));
printf("%ld\n", atol("40000"));
printf("%g\n", atof("2.5e3"));
printf("%g\n", atof("-0.125"));
return 0;
}
The conversions report no errors: a string without a number gives 0, and
trailing text is ignored. A function that does not return an
int must be declared before it is called, as the
functions article explains with
atof. Here the declarations come from the header
<stdlib.h>.
$ gcc -std=c89 -pedantic -Wall -Wextra -o numconv numconv.c $ ./numconv 1978 -42 0 40000 40000 2500 -0.125
V7 UNIX has no <stdlib.h>. Its headers cover the
standard I/O library, the character classes, and the maths library; a
program declares the other functions itself, as the book does. For the
PDP-11 runs in this and the following articles, the include line is
replaced by the declarations of the time, char *malloc(),
*calloc(), *getenv(); double atof(); long atol();, and the rest of
the listing is unchanged. 40000 does not fit in the 16-bit
int of the PDP-11, so atoi wraps it around,
while atol converts it correctly.
$ cc numconv.c $ a.out 1978 -42 0 -25536 40000 2500 -.125
Mathematical functions
The header <math.h> declares the mathematical
functions, all of which take and return double values. They
are in the maths library, which must be named when the program is linked:
-lm at the end of the compile command.
#include <stdio.h>
#include <math.h>
int main()
{
int i;
double x, pi;
printf("%6s %10s %10s %10s\n", "x", "sqrt", "log", "exp");
for (i = 1; i <= 5; i++) {
x = i;
printf("%6.1f %10.6f %10.6f %10.4f\n", x, sqrt(x), log(x), exp(x));
}
pi = 4 * atan(1.0);
printf("pi = %.15f\n", pi);
printf("sin(pi/6) = %g, cos(pi/3) = %g\n", sin(pi / 6), cos(pi / 3));
printf("pow(2, 10) = %g, pow(2, 0.5) = %g\n", pow(2.0, 10.0), pow(2.0, 0.5));
printf("floor(-2.5) = %g, ceil(-2.5) = %g, fabs(-2.5) = %g\n",
floor(-2.5), ceil(-2.5), fabs(-2.5));
return 0;
}
sqrt, log, and exp fill a small
table. log is the natural logarithm. The trigonometric
functions work in radians; four times the arc tangent of 1 is π.
pow(x, y) raises x to the power
y, floor and ceil round down and
up, and fabs returns the absolute value of a
double. The loop counts with an int and converts
it: the V7 compiler cannot apply ++ to a
double and stops with No code table for op:
++post.
$ gcc -std=c89 -pedantic -Wall -Wextra -o maths maths.c -lm
$ ./maths
x sqrt log exp
1.0 1.000000 0.000000 2.7183
2.0 1.414214 0.693147 7.3891
3.0 1.732051 1.098612 20.0855
4.0 2.000000 1.386294 54.5982
5.0 2.236068 1.609438 148.4132
pi = 3.141592653589793
sin(pi/6) = 0.5, cos(pi/3) = 0.5
pow(2, 10) = 1024, pow(2, 0.5) = 1.41421
floor(-2.5) = -3, ceil(-2.5) = -2, fabs(-2.5) = 2.5
Storage from calloc
The size of an array is fixed when the program is compiled. When the size
is known only at run time, the program asks the library for storage.
calloc(n, size) returns a pointer to space for
n objects of size bytes each, filled with zeros,
or NULL when there is no more memory. free(p)
gives the space back.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *v;
int i, n;
if (scanf("%d", &n) != 1 || n < 1) {
fprintf(stderr, "squares: need a positive count\n");
return 1;
}
v = (int *) calloc(n, sizeof(int));
if (v == NULL) {
fprintf(stderr, "squares: out of memory\n");
return 1;
}
printf("v[%d] = %d after calloc\n", n - 1, v[n - 1]);
for (i = 0; i < n; i++)
v[i] = i * i;
for (i = 0; i < n; i++)
printf("%d ", v[i]);
printf("\n");
free((char *) v);
return 0;
}
In K&R C, calloc returns a char pointer,
which the cast converts to a pointer to int; free receives a
char pointer in the same way. After the call, the pointer is
used like an array name. Space from calloc must not be used
after it has been freed. The linked lists
article allocates with malloc, and the
storage allocator article shows how such an
allocator works.
$ gcc -std=c89 -pedantic -Wall -Wextra -o squares squares.c $ echo 6 | ./squares v[5] = 0 after calloc 0 1 4 9 16 25
Random numbers
rand returns the next number of a pseudo-random sequence.
srand(seed) starts the sequence at another place; the same
seed always gives the same numbers.
#include <stdio.h>
#include <stdlib.h>
#define ROLLS 600
int main()
{
int i, count[7];
srand(1978);
for (i = 0; i < 5; i++)
printf("%d ", rand());
printf("\n");
for (i = 1; i <= 6; i++)
count[i] = 0;
for (i = 0; i < ROLLS; i++)
count[rand() % 6 + 1]++;
for (i = 1; i <= 6; i++)
printf("%d: %d\n", i, count[i]);
return 0;
}
The program prints the first five numbers after srand(1978)
and then rolls a die 600 times. rand() % 6 gives a number
from 0 to 5, and adding 1 makes it a die. Each face comes up about a
hundred times. The GNU C library returns numbers up to 2147483647.
$ gcc -std=c89 -pedantic -Wall -Wextra -o dice dice.c $ ./dice 764525230 1166756002 246995063 1398194929 1040890819 1: 104 2: 97 3: 97 4: 100 5: 94 6: 108
The V7 rand uses another formula and returns numbers up to
32767, so the same seed gives a different sequence and different rolls.
A program that needs the same random numbers on every machine must bring
its own generator, like the one in the scope
article.
$ cc dice.c $ a.out 13882 12345 29320 29846 10706 1: 88 2: 100 3: 105 4: 106 5: 99 6: 102
Running a command
system(s) passes the string s to the shell as a
command and waits for it to finish. The command writes to the same
terminal as the program. The return value contains the exit status of the
command in its second byte.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int status;
status = system("echo Hello there from the shell");
printf("status %d\n", status);
status = system("ls missing.txt");
printf("status %d\n", status);
status = system("exit 3");
printf("status %d, exit code %d\n", status, status >> 8);
return 0;
}
The echo command succeeds, and the status is 0. The
ls command fails, writes its own message, and exits with 2,
which system returns as 512. Shifting the value right by
eight bits gives the exit code, here 3. The program's own output is line
buffered on a terminal, so its lines and those of the commands appear in
order.
$ gcc -std=c89 -pedantic -Wall -Wextra -o command command.c $ ./command Hello there from the shell status 0 ls: cannot access 'missing.txt': No such file or directory status 512 status 768, exit code 3
The return value depends on the command. The V7 ls reports a
missing file with a shorter message and still exits with 0.
$ cc command.c $ a.out Hello there from the shell status 0 missing.txt not found status 0 status 768, exit code 3
Time
The header <time.h> declares the time functions. UNIX
counts time in seconds since the start of 1970, kept in a
long. time(&t) stores the current time in
t, ctime turns it into a string, and
localtime breaks it into a structure of local date and time
fields.
#include <stdio.h>
#include <time.h>
int main()
{
long now;
struct tm *tp;
time(&now);
printf("%ld seconds since 1970\n", now);
printf("%s", ctime(&now));
tp = localtime(&now);
printf("year %d, month %d, day %d, weekday %d\n",
tp->tm_year, tp->tm_mon, tp->tm_mday, tp->tm_wday);
printf("day %d of the year\n", tp->tm_yday + 1);
return 0;
}
The string from ctime ends with a newline. The fields of
struct tm count in their own ways: the year from 1900, the
month from 0, the weekday from Sunday as 0, and the day of the year from
0. A year 2000 printed as "19%d" came out as 19100, a common
bug of programs written with two-digit years in mind.
$ gcc -std=c89 -pedantic -Wall -Wextra -o clock clock.c $ ./clock 1796472719 seconds since 1970 Sat Dec 5 13:11:59 2026 year 126, month 11, day 5, weekday 6 day 339 of the year
The simulated PDP-11 has no clock that runs while it is switched off. V7 takes the time from its file system at boot, and the date has never been set on this machine, so it lives in September 1988, in the time zone compiled into its library.
$ cc clock.c $ a.out 590924865 seconds since 1970 Thu Sep 22 05:47:45 1988 year 88, month 8, day 22, weekday 4 day 266 of the year
Source
Dennis Ritchie: C Reference Manual (1975)
In this article we have used the library functions of K&R C:
atoi, atol, and atof, the maths
library with -lm, calloc and free,
rand and srand on two machines,
system and its return value, and the time functions. The
library's sort and search, qsort and bsearch,
are covered in sorting and searching. The next
article goes below the library to the UNIX
interface. Modern C covers some of these functions in
atoi and
malloc and free.
Author
List all K&R C tutorials.