0% found this document useful (0 votes)
35 views66 pages

1 - C Language

1 - C Language

Uploaded by

ranbir singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views66 pages

1 - C Language

1 - C Language

Uploaded by

ranbir singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

A Crash Course in C

Jalal Kawash
2

Section Objectives
At the end of this section you will
1. Learn how to write programs in C
2. Use C pointers and athematic
3. Exploit I/O files
3

Outline
1. Basics
2. Functions
3. Branching and looping
4. Arrays
5. Pointers
6. Structures and memory allocation
7. Files
8. Mixing C and Assembly
4
5

Example C Program
6

Basic Data Types


Type Bytes Use
int 4
char 1
float 4
double 8
short 2 short int
long 8 long int
unsigned 4 unsigned int
7

Conversion and Casting


• C can do type conversions
• In general, a smaller-size type can be converted
to a larger-size type
▫ E.g. float = int
▫ int = short int

• Explicit conversion is done as follows:


▫ (datatype) expression
▫ avg = (float) sum/total
8

Basic Operators
• Addition (a+b)
• Subtraction (a-b)
• Multiplication (a*b)
• Division (a/b)
• Modulus division (a%b)
9
10

Functions
11

Value Parameters
• Do not change outside the function

Output: 0, 0
12

Reference Parameters
• Change outside the function
*n is a pointer
= variable
holding the
address on n

&n = address
of n

Output: 8, 9
13

Command-line Arguments
• Mechanism to collect user input from the command line:
prog <list of arguments>
• The main method can have two arguments:
▫ argc = argument count
▫ argv = argument vector

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

}
14

Command-line Arguments
• argc is computed by the compiler
• argv[0] = program name
15
16
17

Comparison and Logical Operators


• Comparison: ==, !=, <=, >=

• Logical:
▫ AND: &&
▫ OR: ||
▫ NOT: !
18

If Statement
19

Switch Statement
20

Bitwise Operators

Bitwise AND &


Bitwise OR |
Bitwise XOR ^
Left Shift <<
Right Shift >>
One’s complement ~
21

Examples
• value = eFlag & mask
• value = eFlag >> n
• value = eFlag << 3
• value ~= eFlag
• value |= eFlag
• value = (~0 ^ eFlag) << 5
22

While Loop
while (condition) {
body
}
23
24

Do-While Loop
do {
body
} while (condition);

Equivalent to:
body
while (condition) {
body
}
25

For Loop
for (initialization; condition; index update){
Body
}

int i;
for(i = 0; i < 100; i++)
printf("%d ",i);
26
27

continue and break

while (…) { while (…) {


… …
if(…) break; if(…) continue;
… …
} }
28
29

Arrays
• To declare:
int y[100];
int x[10][20];

• Static and external (to main()) arrays can be


initialized
static int y[] ={1,2,3,4,5,6};
int x[2][3] = {1,2,3,4,5,6}
// row major
30
31
32

Pointers
• A variable that contains an address (for another
object in memory)
• The address operator & returns the address of a
variable
• The indirection operator * declares a pointer
variable
33

Pointers Example
Variable n at some address abc
int n = 100;
abc 100
int *ptr; Variable ptr at some address fgh

fgh ?
ptr = &n; fgh abc
Variable m at some address lmn
int m = *ptr
lmn 100
34

Pointers Example Variable n at some address abc

abc 100
Variable ptr at some address fgh
int *m; fgh abc
Variable m at some address lmn

m = ptr; lmn abc


35

Pointer and Float Types


An address is an integer
float f, *g

• g = f or f = g
▫ Not allowed; compiler error
36

Pointer and Integer Types


int m, *n
•n = m
▫ Allowed, compiler warning
• n = (int*) m
▫ Allowed, manual address setting
•m = n
▫ Allowed, compiler warning
• m = (int) n
▫ Allowed, processing the address
37

Arrays and Pointers


• The array name (a) is a pointer to the first
element in an array (a[0])

int a[N], *ptr;


ptr = a; // array has two names now

ptr+n or a+n refer to a[n]


38
39

Pointer Arithmetic
int a[N], *ptr;
ptr = a; // array has two names now
ptr+n or a+n refer to a[n]

• a and ptr must be the same type


• a+n is n “type size” from a
• Type size depends on the type of a
▫ 4 bytes for int, 1 for char, 8 for long, etc …
40

Byte Addresses Memory Bytes

short *ptr; ptr ptr + 0

ptr + 1

ptr + 2

ptr + 3
41

Byte Addresses Memory Bytes

char *ptr; ptr + 0

ptr + 1

ptr + 2

ptr + 3

ptr + 4

ptr + 5

ptr + 6

ptr + 7
42

Byte Addresses Memory Bytes

int *ptr; ptr ptr + 0

ptr + 1
43

Pointer Arithmetic
• A pointer may be displayed as an unsigned
variable
• Pointers can be incremented or decremented
ptr++;
ptr -= 2;
44

Pointer Arithmetic Examples


float a[100], *fptr;
fptr = &a[0]; // same as fptr = a;

• The following equalities hold


• fptr + 5 == &a[5]
• ++fptr + 5 == &a[6]

• *(fptr + 5) == a[5]
• *(++fptr + 5) == a[6]
45

Pointer Arithmetic Examples


float a[100], *fp;
fp = &a[0];
• The following equalities hold
• *fp == a[0]
• *(fp) == a[0]
• *(fp + 6) == a[6]
• *(fp + 6) == *(a + 6)
46

Examples of Operations on Pointers


1. Obtaining the pointer’s address
int n,*p1,*p2;
p1 = &n;
p2 = &p1;

2. A pointer can be declared as a pointer to a


pointer
int **p2;
47

Examples of Operations on Pointers


3. Adding or subtracting
p1++;

4. Indirect operator
int n,m,*p1,*p2;
p1 = &n;
p2 = &m
*p1 = 20; \\ assign 20 to n
*p2 = 4 + (*p1)
\\ assign 4 + the value of n to m
48

Examples of Operations on Pointers


5. Finding the address of a pointer
p2 = &p1;
6. Finding the difference between two pointers
49

Strings
• A string is a character array terminated with NULL

char *name; \\ name[i] is a char


char *name[10]; \\ name[i] is a string
50

Pointers to Functions
• Declared as
type (*funcName)();

• Example: int (*f1)();


▫ Declares a pointer to a function that returns int

• Careful: int *f1();


▫ Declares a function that returns a pointer to int
51

Pointers to Functions
#include <stdio.h>
int isEven(int n){ return !(n%2);}
int isOdd(int n){ return (n%2);}

int main() {
int (*foo)(int);

foo = &isEven;
int m = foo(2);
/* Also can be called as */
m = (*foo)(2);

foo = &isOdd;
m = foo(2);

return 0;
}
52
53

Structures
• Groups variables into a record
struct Student {
long int id;
char fname[20];
char lname[20];
};

struct cpsc Student[50];


cpsc[15].id = 12345678;
54

Unions
• Similar to structures in syntax, but only holds the value
for one member only
• i.e., defines a singe variable
• The size is the size of the largest member

union Answers {
int answer1;
float answer2;
} someAnswers;

someAnswers.answer1 = 12;
someAnswers.answer2 = 15.5;
\\ erases answer1!
55
56

Memory Allocation
• Declaring a pointer to a buffer will only reserve
memory for the pointer, not the buffer
• Functions to allocate (reserve) memory in C:
▫ malloc()
▫ alloc()
▫ realloc()
▫ calloc()
▫ free()
57

ptr = malloc(size)
• Allocates size contiguous bytes
• ptr is a pointer to char type
• If allocation fails, malloc returns 0
• Include #stdlib.h

unsigned int size = 1024;


char *ptr;

ptr = malloc(size);
58

Allocating a buffer of 1024 floats

unsigned int size = 1024;


float *ptr;

ptr = (float *)
malloc((sizeof) float) * size);

59

ptr = alloc(size)

• Not available in all systems


• Similar to malloc but initializes the buffer to
zeros.
• Not supported in GCC
60

ptr = realloc(ptr,newSize)
• Reallocates the old buffer of ptr to newSize
• Buffer can grow or shrink

unsigned int size = 1024;


char *ptr;

ptr = malloc(size);

ptr = realloc(ptr, size*2);
61

ptr = calloc(n,objSize)
• Allocates a buffer of objects
• Used to allocate memory for non-simple types
▫ Such as structures
• n is the buffer size
• objSize is the size of individual object size
62

free(ptr)

• Frees the space originally allocated with pointer


ptr
63
64

Files
• Declare: FILE *inFile, *outFile;
• Open: inFile = fopen(“fork.c”,”r”);
outfile = fopen(“fork1.c”,”w”);
• Read: fscanf(inFile, “%c”, &ch);
• Write: fprintf(outFile, “%c”, ch);
• Close: fclose(inFile);
fclose(outFile);
65

Files
• EOF: Delimits the end of a file
while (ch = fgetc(inFile) != EOF) {…}

• fopen returns NULL if unsuccessful


66

You might also like