Page 129 - Programming Microcontrollers in C
P. 129
114 Chapter 2 Advanced C Topics
will cause the data to be printed to the left edge of the field. Other
wise, the data will print to the extreme right edge of the field.
Formatted input is also provided in C. The three formatted
input functions are
int scanf(char* format,arg1,arg2,...);
int sscanf(char* string,char*
format,arg1,arg2,...);
int fscanf(FILE* fp,char* format,arg1,arg2,...);
The first of these functions reads formatted data from the standard
input, the second reads formatted data from a string in memory, and
the third reads formatted data from an open file fp. There is a sig
nificant difference between the formatted inputs and outputs. Recall
that the arguments in the formatted outputs are data values. In the
formatted inputs, all arguments must be pointers to locations in
memory that can hold the data types specified in the data string. If
the program should contain
int i;
.
.
.
scanf(“%d”,i); /* BAD */
the program will probably compile, the compilers will not note an
error, and the program will crash because the scanf() argument is
not a pointer. It is generally recommended that you avoid use of the
scanf() function.
Memory Management
There are two functions in C that allow dynamic memory man
agement. The function
void* malloc(size_t n);
returns a pointer to a block of memory that is n bytes long. This
memory is uninitialized. malloc() (and calloc() below) re
turns a pointer to a block of memory of the type void. Therefore,
before it can be used, the return pointer must be cast onto the data
type that the program requires. In this case, an assignment of the
return value to a pointer of the correct type will work. If this step is