[ Pobierz całość w formacie PDF ]

stack the usual "local" way, and one in the heap using malloc(). Other than the different
allocations, the two are syntactically similar in use.
{
int a[1000];
int *b;
b = (int*) malloc( sizeof(int) * 1000);
assert(b != NULL); // check that the allocation succeeded
a[123] = 13; // Just use good ol' [] to access elements
b[123] = 13; // in both arrays.
free(b);
}
Although both arrays can be accessed with [ ], the rules for their maintenance are very
different....
Advantages of being in the heap
" Size (in this case 1000) can be defined at run time. Not so for an array like "a".
" The array will exist until it is explicitly deallocated with a call to free().
" You can change the size of the array at will at run time using realloc(). The following
changes the size of the array to 2000. Realloc() takes care of copying over the old
elements.
...
b = realloc(b, sizeof(int) * 2000);
assert(b != NULL);
Disadvantages of being in the heap
" You have to remember to allocate the array, and you have to get it right.
" You have to remember to deallocate it exactly once when you are done with it, and you
have to get that right.
" The above two disadvantages have the same basic profile: if you get them wrong, your
code still looks right. It compiles fine. It even runs for small cases, but for some input
cases it just crashes unexpectedly because random memory is getting overwritten
somewhere like the smiley face. This sort of "random memory smasher" bug can be a
real ordeal to track down.
40
Dynamic Strings
The dynamic allocation of arrays works very well for allocating strings in the heap. The
advantage of heap allocating a string is that the heap block can be just big enough to store
the actual number of characters in the string. The common local variable technique such
as char string[1000]; allocates way too much space most of the time, wasting
the unused bytes, and yet fails if the string ever gets bigger than the variable's fixed size.
#include
/*
Takes a c string as input, and makes a copy of that string
in the heap. The caller takes over ownership of the new string
and is responsible for freeing it.
*/
char* MakeStringInHeap(const char* source) {
char* newString;
newString = (char*) malloc(strlen(source) + 1); // +1 for the '\0'
assert(newString != NULL);
strcpy(newString, source);
return(newString);
}
41
Section 7
Details and Library Functions
Precedence and Associativity
function-call() [] -> . L to R
! ~ ++ -- + - *(ptr deref) sizeof &(addr of) R to L
(all unary ops are the same)
* / % L to R
(the top tier arithmetic binary ops)
+ - L to R
(second tier arithmetic binary ops)
= L to R
== != L to R
in order: & ^ | && || L to R
(note that bitwise comes before boolean)
= and all its variants R to L
, (comma) . L to R
A combinations which never works right without parens: *structptr.field
You have to write it as (*structptr).field or structptr->field
Standard Library Functions
Many basic housekeeping funcions are available to a C program in form of standard
library functions. To call these, a program must #include the appropriate .h file. Most
compilers link in the standard library code by default. The functions listed in the next
section are the most commonly used ones, but there are many more which are not listed
here.
stdio.h file input and output
ctype.h character tests
string.h string operations
math.h mathematical functions such as sin() and cos()
stdlib.h utility functions such as malloc() and rand()
assert.h the assert() debugging macro
stdarg.h support for functions with variable numbers of arguments
setjmp.h support for non-local flow control jumps
signal.h support for exceptional condition signals
time.h date and time
42
limits.h, float.h constants which define type range values such as INT_MAX
stdio.h
Stdio.h is a very common file to #include -- it includes functions to print and read strings
from files and to open and close files in the file system.
FILE* fopen(const char* fname, const char* mode);
Open a file named in the filesystem and return a FILE* for it. Mode = "r" read,"w"
write,"a"append, returns NULL on error. The standard files stdout, stdin,
stderr are automatically opened and closed for you by the system.
int fclose(FILE* file);
Close a previously opened file. Returns EOF on error. The operating system closes all
of a program's files when it exits, but it's tidy to do it beforehand. Also, there is
typically a limit to the number of files which a program may have open
simultaneously.
int fgetc(FILE* in);
Read and return the next unsigned char out of a file, or EOF if the file has been
exhausted. (detail) This and other file functions return ints instead of a chars because
the EOF constant they potentially is not a char, but is an int. getc() is an alternate,
faster version implemented as a macro which may evaluate the FILE* expression
more than once.
char* fgets(char* dest, int n, FILE* in)
Reads the next line of text into a string supplied by the caller. Reads at most n-1
characters from the file, stopping at the first '\n' character. In any case, the string is '\0'
terminated. The '\n' is included in the string. Returns NULL on EOF or error.
int fputc(int ch, FILE* out);
Write the char to the file as an unsigned char. Returns ch, or EOF on err. putc() is an
alternate, faster version implemented as a macro which may evaluate the FILE*
expression more than once.
int ungetc(int ch, FILE* in);
Push the most recent fgetc() char back onto the file. EOF may not be pushed back.
Returns ch or EOF on error.
int printf(const char* format_string, ...);
Prints a string with values possibly inserted into it to standard output. Takes a variable
number of arguments -- first a format string followed by a number of matching
arguments. The format string contains text mixed with % directives which mark
things to be inserted in the output. %d = int, %Ld=long int, %s=string, %f=double,
%c=char. Every % directive must have a matching argument of the correct type after
the format string. Returns the number of characters written, or negative on error. If
the percent directives do not match the number and type of arguments, printf() tends
to crash or otherwise do the wrong thing at run time. fprintf() is a variant which takes
an additional FILE* argument which specifies the file to print to. Examples...
printf("hello\n"); prints: hello
printf("hello %d there %d\n", 13, 1+1); prints: hello 13 there 2
printf("hello %c there %d %s\n", 'A', 42, "ok"); prints: hello A there 42 ok
43
int scanf(const char* format, ...)
Opposite of printf() -- reads characters from standard input trying to match elements
in the format string. Each percent directive in the format string must have a matching
pointer in the argument list which scanf() uses to store the values it finds. scanf()
skips whitespace as it tries to read in each percent directive. Returns the number of
percent directives processed successfully, or EOF on error. scanf() is famously
sensitive to programmer errors. If scanf() is called with anything but the correct
pointers after the format string, it tends to crash or otherwise do the wrong thing at
run time. sscanf() is a variant which takes an additional initial string from which it
does its reading. fscanf() is a variant which takes an additional initial FILE* from
which it does its reading. Example...
{
int num;
char s1[1000];
char s2[1000];
scanf("hello %d %s %s", &num, s1, s2);
} [ Pobierz całość w formacie PDF ]

  • zanotowane.pl
  • doc.pisz.pl
  • pdf.pisz.pl
  • pomorskie.pev.pl
  • Archiwum

    Home
    Morey Trish SpeśÂ‚nione marzenie
    Cabot Particia Amazonka
    Arsan Antonin Emmanuelle
    Gordon R. Dickson The Last Dream
    Alexander, Lloyd Chronicles of Prydain 02 The Black Cauldron
    Ian Watson Hard Questions
    G.K.Chesterton The.Wisdom.of.Father.Brown
    CWIHP Bulletin nr 5 part 1 Germany 1953; Hungary 1956
    Graham Masterton The Pariah
    Niespodzianka na 6 liter
  • zanotowane.pl
  • doc.pisz.pl
  • pdf.pisz.pl
  • ramtopy.keep.pl