C Programming Language

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

int main(void)

"main" is special. Your program begins executing at the beginning of main. This means that every program must have a main somewhere.

Difference between: int a[10][20]; and int *b[10]; when referencing a[3][4] or b[3][4].

'a' is a true two-dimensional array: 200 int-sized locations have been set aside. For 'b', the definition only allocates 10 pointers and does not initialize them; initialization must be done explicitly, either statically or with code. - Assuming that each element of b does point to a 20 element array, then there will be 200 int set aside, plus 10 cells for the pointers.

Difference between an array name and a pointer?

1. A pointer is a variable, so 'pa = a' and 'pa++' are legal. 2. An array name is not a variable; constructions like 'a = pa' and 'a++' are illegal.

What are the legal operations on a structure?

1. Copying it 2. Assigning to it as a unit 3. Taking its address with & 4. Accessing its members

int a[10];

1. Defines an array 'a' or size 10 2. A block of 10 consecutive objects named a[0], a[1], ... , a[9]

External, Static, and Automatic Variable Default Initialization

1. External Variables - Initialized to zero by default 2. Static Variables - Initialized to Zero by default 3. Automatic Variables - Undefined Values (garbage values) by default

While Loop

1. The condition in parentheses is tested. 2. If it is true, the body of the loop is executed. 3. Then the condition is re-tested and if true, the body is executed again. 4. When the test becomes false the loop ends, and execution continues at the statement that follows the loop.

int *pa; pa = &a[0];

1. pa is a pointer to an integer 2. pa set to point to element zero of a (pa contains the address of a[0])

header file

A centralized file that contains the definitions and declarations shared among files. Included by using #include at the front of each source file.

'c'

A character written between single quotes represents an integer value equal to the numerical value of the character in the machine's character set. It is called a character constant.

Structure

A collection of one or more variables, possibly of different types, grouped together under a single name for convenient handling. - They help to organize complicated data, particularly in large programs, because they permit a group of related variables to be treated as a unit instead of as separate entities.

Optional Flag or Parameter

A common convention for C programs on UNIX systems is that an argument that begins with a minus sign (-) introduces an optional flag or parameter.

Function Prototype

A declaration of a function that specifies the function's name and type signature but omits the function body.

void *

A generic pointer to void. It is used to hold any type of pointer but cannot dereference itself.

printf("hello, world\n")

A library function that prints output, in this care the string of characters between the quotes.

Switch Statement

A multi-way decision that tests whether an expression matches one of a number of constant integer value and branches accordingly. 1. Each case is labeled by one of more integer-valued constants. 2. If a case matches the expression value, execution starts at the case. All case expressions must be different. 3. The case labeled default is executed is executed if none of the other cases are satisfied. 4. Cases and the default can occur in any order. P.S. - After the code for one case is done, execution falls through to the next unless you leave the switch with 'break' or 'return'.

'\0' in an Array

A null character ('\0') is put at the end of an array to mark the end of the string of characters.

Pointer Arithmetic

A pointer in C is an address, which is a numeric value. Therefore, you can perform arithmetic operations on a pointer just as you can on a numeric value. - There are four arithmetic operators that can be used on pointers: ++, --, +, and -

"hello, world\n"

A sequence of characters in double quotes is called a character string or string constant.

char

A single byte, capable of holding one character in the local character set. 1. Unsigned: 255 2. Signed max: 127 3. Signed min: -128

Initialization of Character Arrays

A string may be used instead of the braces and commas notation. Ex: char pattern[] = "ould"; is the same as: char pattern[] = { 'o', 'u', 'l', 'd', '\0' }; - Remember to add the terminating '\0' to the size of the character array.

Side Effect

A variable is changed as a by-product of the evaluation of an expression.

Parameter

A variable named in the parenthesized list in a function definition. Ex: int power(int base, int n);

Pointer

A variable that contains the address of a variable. It is a group of cells that can hold an address. Ex: char *name int *name void *name

Union

A variable that may hold (at different times) objects of different types and sizes. They provide a way to manipulate different kinds of data in a single area of storage. - It's a structure in which all members have offset zero from the base, the structure is big enough to hold the "widest" member, and the alignment is appropriate for all of the types.

typedef

Adds a new name for an existing data type. - We capitalize names for typedefs to make them stand out. Ex: Creates a new type keyword called Treenode (a structure) and Treeptr (a pointer to the structure).

"I am a string"

An array of characters. In the internal representation, the array is terminated with the null character '\0' so that programs can find the end. - The length in storage is thus one more than the number of characters between the double quotes.

int

An integer, typically reflecting the natural size of integers on the host machine. 1. Unsigned: 4294967295 2. Signed max: 2147483647 3. Signed min: -2147483648

Structure Tag

An optional name that may follow the word struct. - The tag names this kind of structure, and can be used subsequently as a shorthand for the part of the declaration in braces. Ex: struct point { ... };

&&

And.

Declaration

Announces the properties of variables; it consists of a type name and a list of variables. Ex: int lower, upper, step;

//

Any characters after // are ignored by the compiler; they may be used freely to make a program easier to understand.

argc

Argument Count. The number of command-line arguments the program was invoked with.

argv

Argument Vector. A pointer to an array of character strings that contain the arguments, one per string.

Cast

As if the expression were assigned to a variable of the specified type, which is then used in place of the whole construction. Construction: (type-name) expression Ex: sqrt( (double) n); - The cast produces the value of n in the proper type; n itself is not altered.

Assignment Operators

Assigns the value of its right operand to its left operand. Ex: += , -= , *= , /= , %=

a[i] can also be written as?

C converts it to *(a + i) immediately. 'a + i' is the address of the i-th element beyond a.

#define name replacement_text

Calls for a macro substitution of the simplest kind - subsequent occurrences of the token 'name' will be replaced by the 'replacement_text'. Ex: #define STEP 20

const

Can be applied to the declaration of any variable to specify that its value will not be changed. It can be used with array arguments to indicate that the function does not change the array. Ex: 1. const int 1234; 2. int strlen(const char[ ]);

break Statement

Causes the innermost enclosing loop or switch to be exited immediately. It provides an early exit from a for, while, do loops & switch statements.

continue Statement

Causes the next iteration of the enclosing for, while, or do loop to begin. Applies only to loops, not switch statements.

#if, #elif, #else, #endif

Conditional statements that are evaluated using preprocessing. Evaluates a constant integer expression. 1. If the expression is non-zero, subsequent lines until an #endif or #elif or #else are included. - defined('name') is a 1 if the 'name' is defined, otherwise it is a 0.

Binary Tree

Contains 1 "node" per distinct work; each contains: 1. a pointer to the text of the word 2. a count of the number of occurrences 3. a pointer to the left child node 4. a pointer to the right child node - A node may not have more than two children Ex: "now is the time for all good men to come to the aid of their party"

strcpy(s, t)

Copies the string t to the string s.

Block

Declarations and statements together grouped together using braces ({ and }). Used when expressions have more than one statement to execute. Ex: Functions, if, else, while, for

struct { ... } x, y, z;

Declares x, y, z to be variables of the named type and causes space to be set aside for them. - A structure declaration that is not followed by a list of variables reserves no storage; it merely describes a template or the shape of a structure.

External Variables

Defined outside of any function, thus potentially available to many functions. They are permanent, so they retain values from one function invocation to the next.

struct point maxpt = { 320, 200 };

Defines a variable 'pt' which is a structure of type struct point. - A structure can be initialized by following its definition with a list of initializers, each a constant expression, for the members.

*

Dereferencing operator. When applied to a pointer, it accesses the object the pointer points to.

double

Double-precision floating point. 1. Max: 1.79769e+308 2. Min: 2.22507e-308

free()

Frees the space pointed to. - Freeing also causes a search of the free space list malloc uses to find the right place to insert the block being freed. - If the block being freed is adjacent to a free block on either side, it is coalesced with it into a single bigger block, so storage does not become too fragmented. - Determining adjacency is easy because the free list is maintained in order of increasing address.

&

Gives the address of an object. Only applied to objects, variables, and arrays in memory. Ex: p = &c; - Assigns the address of c to the variable p. p is said to "point to" c.

Arguments - Call by Value

In C, functions arguments are passed "by value". This means that the called function is given the values of its arguments in temporary variables rather than originals and it cannot directly alter a variable in the calling function, it can only alter its private, temporary copy.

;

In C, the semicolon is a statement terminator.

++

Increment by one.

Initialization of Arrays

Initialized by following its declaration with a list of initializers enclosed in braces and separated by commas. Ex: int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31} - When the size is omitted, the compiler will computer the length by counting the inializers.

==

Is equal to.

The Static Declaration

It is applied to an external variable or function to limit the scope of that object to the rest of the source file being compiled. The names will not conflict with the same names in other files of the same program. Ex: static char buf[BIFSIZE];

int *pa; pa = &a[0]; Then: *(pa + 1) equals?

It refers to the contents of a[1]. 1. pa + 1 is the address of a[i] 2. *(pa + i) is the contents of a[i]

Automatic Variables

Local variables in a function that come into existence only when the function is called, and disappears when the function is exited.

long

Long integer. 1. Unsigned: 18446744073709551615 2. Signed max: 9223372036854775807 3. Signed min: -9223372036854775808

char daytab[2][5] = {{0,1,2,3,4,5}, {6,7,8,9,10}};

Multi-dimensional Array. - If a two-dimensional array is to be passed to a function, the parameter declaration in the function must include the number of columns; the number of rows is irrelevant since what is passed is, as before, a pointer to an array of rows, where each row is an array of 13 ints. Ex: f(int daytab[2][5]);

\n

Newline character, which when printed advances the output to the left margin on the next line.

!=

Not equal to.

||

Or.

putchar(c)

Prints that contents of the integer variable c as a character, usually on the screen.

Function

Provides a convenient way to encapsulate some computation, which can then be used without worrying about its implementation.

getchar()

Reads the next input character from a text stream and returns that as its value. Ex: c = getchar()

Declaration of external variable

Refers to places where the property of the variable is stated but no storage is allocated. They do not create the variable or reserve storage for them. Ex: extern double val[];

p -> member-of-structure

Refers to the particular member of a structure. - The operator -> is a minus sign immediately followed by a greater than sign.

Definition of an external variable

Refers to the place where the variable is created and assigned storage. Ex: double val[MAXVAL];

afree(n)

Releases the storage thus acquired so it can be re-used later. - The calls to afree must be made in the opposite order to the calls made on alloc. - The storage managed by alloc and afree is a stack, or last-in, first-out list.

malloc()

Requests space from the operating system as needed. - Space managed by malloc is not contiguous. - It's free storage is kept as a list of free blocks. - Each block contains a size, a pointer to the next block, and the space itself. - Blocks are kept in order of increasing storage address, and the last block (highest address) points to the first.

alloc(n)

Returns a pointer 'p' to n-consecutive character positions, which can be used by the caller of the function for storing characters.

Return value of: char *month_name(int n);

Returns a pointer to a character string.

Assignment Statements

Set the variables to their initial values. Ex: lower = 0;

short

Short integer. 1. Unsigned: 65535 2. Signed max: 32767 3. Signed min: -32768

float

Single-precision floating point or numbers that have a fractional part. 1. Max: 3.40282e+38 2. Min: 1.17549e-38

#ifdef, #ifndef

Specialized forms that test whether a name is defined.

#include <stdio.h>

Standard Input/Output Library

struct point *pp;

Structure pointer to the point structure. - pp points to a point structure, and (*pp) .x and (*pp) .y are members.

do-while Loop

Tests the termination condition at the bottom after each pass through the loop body; the body is always executed at least once. 1. The statement is executed. 2. The expression is executed. If it is true, the statement is evaluated again and so on. 3. When the expression becomes false, the loop terminates.

int (*comp)(void *, void *)

The declaration states that comp is a pointer to a function that has two void * arguments and returns an int. - 'comp' is a pointer to the function - '*comp' is the function

n++ vs ++n

The expression ++n increments n before its value is used, while n++ increments n after its value has been used. Ex: int n =5; x = n++; sets x to 5 x = ++n; sets x to 6

Hash Search

The incoming name is converted into a small non-negative integer, which is then used to index into an array of pointers. An array element points to the beginning of a linked list of blocks describing names that have that hash value. - A block in the list is a structure containing pointers to the name, replacement text, and the next block in the list.

return Statement

The mechanism for returning a value from the called function to its caller. The expression will be converted to the return type of the function if necessary.

else-if Statement

The most general way of writing a multi-way decision. 1. The expressions are evaluated in order. 2. If any expression is true, the block associated with it is executed and this terminates the whole chain.

Scope

The part of the program within which the variable can be used.

Advantage of Pointer Array over Multi-Dimensional Array

The rows of a pointer array may be of different lengths.

structure-name .member

The structure member operator "." connects the structure name and the member name. Ex: pt.x pt.y

size_t

The unsigned integer type returned by the sizeof operator.

What is the value of an array type?

The value is the address of element zero of the array. Thus after assignment: pa = &a[0]; can also be written as: pa = a;

Argument

The value used in a call of the function. Ex: power(2, 1)

Members

The variable names in a structure. - A structure member or tag and an ordinary variable can have the same name without conflict.

TorF: It is illegal for a structure to contain an instance of itself.

True but it is legal for a structure to contain a pointer to the structure, not the structure itself.

TorF: A pointer is constrained to point to a particular kind of object; every pointer points to a specific data type.

True but void *name is an exception. Ex: double *dp -Points to double data types

TorF: The purpose of supplying the size of an array in a declaration is to set aside storage.

True.

TorF: Since pointers are variables themselves, they can be stored in arrays just as other variables can.

True. - If the lines to be sorted are stored end-to-end in one long character array, then each line can be accessed by a pointer to its first character. The pointers themselves can be stored in an array.

TorF: In C, a function is not a variable but it is possible to define pointers to functions.

True. Functions can be assigned to pointers, placed in arrays, passed to functions, returned by functions, and so on. Picture: The qsort function expects an array of pointers, two integers, and a function with two pointer agruments.

TorF: The addition of two pointers is illegal.

True. However, subtraction is legal.

TorF: Valid pointer operations are assignment of pointers of the same type, adding or subtracting a pointer and an integer, subtracting or comparing two pointers to members of the same array, and assigning or comparing to zero.

True. It is not legal to add two pointers, or to multiple or divide or shift or mask them, or to add float or double to them, or even, except for void *, to assign a pointer of one type to a pointer of another type without a cast.

TorF: 'char s[]' the same as 'char *s'?

True. The latter is preferred because it says more explicitly that the parameter is a pointer.

extern

Used if an external variable is to be referred to before it is defined, or if it is defined in a different source file from the one where it is being used.

sizeof( type-name )

Used to compute the size of any object and yields an integer equal to the size of the specified object or type in bytes.

if-else Statement

Used to express decisions. 1. The expression is evaluated; if it is true (non-zero), the block is executed. 2. If it is false, (zero) and there is an else part, that block is executed.

#include <filename>

Used to include the contents of a file during compilation. If the filename is quoted, searching for the file starts where the source code begins. if it is enclosed in < and >, searching follows an implementation-defined rule to find the file.

Recursion

When a function calls itself either directly or indirectly. The solution to a problem depends on solutions to smaller instances of the same problem (as opposed to iteration). - Each invocation of the function gets a fresh set of automatic variables. - Provides no saving in storage, nor is it faster. - But it is more compact, and often much easier to read and understand.

Signed variables

Will allow you to represent numbers both in the positive and negative ranges. Ex: A signed byte can represent -128 to 127.

Unsigned variables

Will only allow you to represent numbers in the positive. They can represent a larger magnitude number than the corresponding signed variable. Ex: An unsigned byte can represent values from 0 to 255

For Loop

Within the parentheses, there are three parts, separated by semicolons: 1. The first part, initialization is done once before the loop proper is entered. 2. The second part is the test or condition that controls the loop. If the condition is true, the body of the loop is executed. 3. Then the increment step is executed and the condition is re-evaluated. The loop terminates when the condition statement becomes false.

Arguments - Call by Reference

You can modify a variable in a function directly by passing in the address of the variable to be set. The called function must declare the parameter to be a pointer and access the variable indirectly through it.

char amessage[] = "now is the time"; vs. char *pmessage = "now is the time";

amessage is an array, just big enough to hold the sequence of characters and '\0' that initializes it. Individual characters within the array may be changed but amessage will always refer to the same storage. On the other hand, pmessage is a pointer, initialized to point to a string constant; the pointer may subsequently be modified to point elsewhere, but the result is undefined if you try to modify the string contents.

char **argv

argv: pointer to pointer to char

void *comp()

comp: function returning pointer to void

void (*comp)()

comp: pointer to function returning void

int *daytab[13]

daytab: array[13] of pointer to int

int (*daytab)[13]

daytab: pointer to array[13] of int

Conditional Expressions

expr1 ? expr2 : expr3; 1. The expression "expr1" is evaluated first. 2. If it is non-zero (true), then the expression "expr2" is evaluated and that is the value of the conditional expression. 3. Otherwise (false), "expr3" is evaluated, and that is the value. Ex: z = (a > b) ? a : b;

char (*(*x[3])())[5]

x: array[3] of pointer to function returning pointer to array[5] of char

char (*(*x())[])()

x: function returning pointer to array[ ] of pointer to function returning char


Kaugnay na mga set ng pag-aaral

Kinetics: Rates and Mechanisms of Chemical Reactions

View Set

A&P II Chapter 25 Fluid, Electrolyte, and Acid-Base Homeostasis NWCC Nickens

View Set

Chap 2 Job-Order Costing: Calculating Unit Product Costs

View Set