C tour

6
1 Tour of C Data Types, Arrays, Strings and Pointers in C 2 Data Types C char short int long float double long double signed/ unsigned – char, short, int, long 3 Like Java, Like C C Operators same as in Java - Arithmetic int i = i+1; i++; i--; i*=2; +, -, *, /, % - Relational and logical <, >, <=, >=, ==, != &&, ||, &, |, ! Syntax same as in Java - if() { } else { } - while() { } - do { } while (); - for(i = 1; i <= 100; i++) { } - switch() {case 1: …} - continue; break; 4 Arrays in C 5 Array Declaration C The dimension must be a constant or a constant expression (needs to be determined at compile time) #define BUFFSIZE 256 #define MAXSIZE 12 int main() { int size = 6; char buffer[BUFFERSIZE]; // elegant declaration // constant integer dimension char buffer[256]; // NOT an elegant declaration // integer literal dimension int dice[BUFFSIZE / 2]; // constant integer expression // used for dimension float rollValue[size]; // NOT valid - size is not a // constant ... 6 Array Initialization C Providing too many initial values causes a compile-time error: int count[MAX] = {1,2,3,4,5,6}; // ERROR! If the number of initial values listed is less than the capacity of the array, the remaining elements are automatically initialized to 0. Thus int count[5] = {2}; is equivalent to int count[5] = {2,0,0,0,0}; #define MAX 5 int count[MAX] = {5, 7, 2, 4, 8}; [0] [1] [2] count [3] [4] 7 2 4 8 5

description

 

Transcript of C tour

Page 1: C  tour

1

1

Tour of C

Data Types, Arrays, Strings and Pointers in C

2

Data Types Ccharshortintlongfloatdoublelong double

signed/ unsigned – char, short, int, long

3

Like Java, Like C COperators same as in Java- Arithmetic

int i = i+1; i++; i--; i*=2;+, -, *, /, %

- Relational and logical<, >, <=, >=, ==, !=&&, ||, &, |, !

Syntax same as in Java- if() { } else { }- while() { }- do { } while ();- for(i = 1; i <= 100; i++) { }- switch() {case 1: …}- continue; break;

4

Arrays in C

5

Array Declaration CThe dimension must be a constant or a constant expression (needs to be determined at compile time)

#define BUFFSIZE 256#define MAXSIZE 12

int main(){

int size = 6;

char buffer[BUFFERSIZE]; // elegant declaration// constant integer dimension

char buffer[256]; // NOT an elegant declaration// integer literal dimension

int dice[BUFFSIZE / 2]; // constant integer expression// used for dimension

float rollValue[size]; // NOT valid - size is not a // constant

...6

Array Initialization C

Providing too many initial values causes a compile-time error:

int count[MAX] = {1,2,3,4,5,6}; // ERROR!

If the number of initial values listed is less than the capacity of the array, the remaining elements are automatically initialized to 0. Thus

int count[5] = {2};

is equivalent to int count[5] = {2,0,0,0,0};

#define MAX 5int count[MAX] = {5, 7, 2, 4, 8};

[0] [1] [2]

count

[3] [4]

7 2 4 85

Page 2: C  tour

2

7

Array Indices CLogically, valid indices for an array range from 0 to MAX-1, where MAX is the dimension of the array

Memory

int A[6]; stands forA[0], A[1], A[2], A[3], A[4] and A[5]

Logically, there is no A[6]!

A[0] A[1] A[2] A[3] A[4] A[5]

8

Out-of-Bounds Array Indices (1) CA common logical error in processing arrays is exceeding the valid index range:

What happens when a statement uses an array index that is out of bounds?

#define MAX 100int someArray[MAX];

someArray[MAX] = 0; // will compile// but run time ERROR !

int i;

for(i = 0; i <= MAX; i++)someArray[i] = 0;

No automatic checking of array indices at run time !

9

Out-of-Bounds Array Indices (2) CThe memory location someArray[100] may :

1. Store a variable declared in your program – that variable will be altered. Since there is no statement that directly assigns a value to that variable, this effect seems very mysterious when debugging.

2. Not be allocated for the use of your program. The result depends on the operating system you are using

Some operating systems, such as Windows95/98 do not carefully monitor memory accesses and your program may corrupt a value that actually belongs to another program Other operating systems, such as Windows NT and Unix, will detect that a memory access violation has occurred and suspend or kill your program

10

Lack of Aggregate Array Operations CAggregate operations refer to operations on an array as a whole, as opposed to operations on individual array elements.

#define MAX 100int x[MAX];int y[MAX];

There are no aggregate operations on arrays:

Assignment x = y; Error !Comparison if (x == y) … Error!I/O printf(“%d”, x); Error! Arithmetic: x = x + y; Error!

11

Strings in C

12

String Declarations CUnlike Java, there is no String data type in C Strings in C are simply arrays of characters terminated with 0 (character ‘\0’)

char some[10]; // need to specify max size

// one way:char msg[6] = {‘H’,‘e’,‘y’,‘ ’,‘!’,‘\0’};

// another way (last 2 places unused):char msg[8] = “Hey !”; // no ‘\0’

// orchar msg[ ] = “Hey !”; // no ‘\0’

memory for 6 characters ( 5 plus the null char ‘\0’ ) automatically allocated

Page 3: C  tour

3

13

Memory Representationchar some[10];

char msg[6] = {‘H’,‘e’,‘y’,‘ ’,‘!’,‘\0’};

char msg[8] = “Hey !”;

char msg[] = “Hey !”;

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]

‘H’‘e’‘y’‘ ’‘!’ 0[0] [1] [2] [3] [4] [5]

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]

‘H’‘e’‘y’‘ ’‘!’ 0

‘H’‘e’‘y’‘ ’‘!’ 0[0] [1] [2] [3] [4] [5]

14

Reading Into a String (1) C#define MAX_BUFFER 20char buffer[MAX_BUFFER];

scanf(“%s”, buffer); // orgets(buffer, MAX_BUFFER);

What if the array is not large enough to hold the input?

- characters will be stored into memory locations past the end of the array

- will result in run-time memory access violation error !

15

Reading Into a String (2) CBetter:

#define MAX_BUFFER 20char buffer[MAX_BUFFER];

fgets(buffer, MAX_BUFFER, stdin);

fgets is similar to gets, but:

- it takes a third argument, in our case standard input

- if stores into buffer no more than MAX_BUFFER chars (extra characters are ignored), so memory violation error won’t occur

16

Functions for Manipulating Strings CC provides a large number of functions for manipulating strings. Four important ones:strlen(s)// returns the length of s

strcpy(toS, fromS)// copy fromS to toS (toS must be large enough)

strcmp(s1, s2)// returns 0 if s1 == s2// returns an integer < 0 if s1 < s2// returns an integer > 0 if s1 > s2

strtok – read the Sun manual pages to find out what this function does

17

Pointers in C

18

What are Pointers? CA pointer is a variable that holds the address of another variable (object)

Suppose that we have an integer variableint i;

and wish to have a pointer point to this variable. Thus we need to know the memory address of i.

How do we know the address of i? ...&i

is the address of i. The operator is called the ADDRESS-OF operator.

&

Page 4: C  tour

4

19

Pointers Made Easy (1) CWe can declare that a pointer iPtr points to an intby saying

int * iPtr;

Suppose that we have:int i = 5;int j = 7;

We can make iPtr point to i by assigning to iPtr the memory location where i is stored. Thus

iPtr = &i;

sets iPtr to point to i.

5

7

100

...

...

(&i) 100

(&j) 180

260

i

j

iPtr

5

iPtr i

20

Pointers Made Easy (2) CWe can also initialize iPtr at the point of declaration:

int i;int * iPtr = &i;

Here is a common error:

int i;

int * iPtr = i; // ERROR: i is not an address

???iPtr i

21

Declaring Pointers CWhen declaring several pointer variables in one statement - the asterisk does not distribute throughout the statement:

int *p, q; int * p;int q;

equivalent to

int * p, * q; int * p;int * q;

equivalent to

22

Dereference * C The value of the data being pointed at is obtained by using the operator *

If p is a pointer value, then

*p

refers to the variable pointed to by p. Since reference is another name for address, the operator * is called dereference operator.

23

Dereference Example C

• A dereferenced pointer behaves exactly like the variable it points to.

p???i

???i

int * p = &i;

p101i

*p = 101;

p102i

(*p)++;int i;

Equivalent to i = 101;

Equivalent to i++;

24

Note the Difference … C

ptr15

i

ptr27

j

Initial state

ptr15

i

ptr27

j

After

ptr1 = ptr2;

starting from initial state

ptr17

i

ptr27

j

After

*ptr1 = *ptr2;

starting from initial state

Page 5: C  tour

5

25

Uninitialized Pointers C Suppose that we have the following declarations:

int i;int * iPtr;*iPtr = 100;

What is the value of iPtr? Undefined. What could happen?- iPtr could hold an address that does not make sense at all,

causing your program to crash if dereferenced.- iPtr could point to an address which is accessible. Then the

assignment *iPtr = 100; would accidentally change some other data, which could result in a crash at a later point. This is a tough error to detect since the cause and symptom may be widely separated in time.

???iPtr i

26

Putting it all Together... C… with the help of a simple example:

Step 1

Step 2

Step 3

int i, value;int * iPtr; // declares iPtr to be a pointer to an integer

i = 510; // Step 1iPtr = &i; // Step 2value = *iPtr; // Step 3

510

i

???

value

???

iPtr

510

i

???

valueiPtr

510

i

510

valueiPtr

27

The null Pointer CThe value of a pointer can be:- some garbage (pointer unassigned)- the address of some variable (eg., int * p = &i; )- the constant 0 (the null pointer, points to absolutely nothing)

somePointer = 0;

This statement does not cause somePointer to point to memory location zero; it guarantees that somePointer does not point to anything

The null pointer is a special pointer value that a program can test for:

if (somePointer == 0) ...

28

Arrays and Pointers

29

Arrays and Pointers CAn array name is basically a constant pointer

Consider the declaration:

char a[3];

The compiler allocates three integers for the array object. These are referenced as a[0], a[1], a[2]and occupy a contiguous block of memory.

The value of a is exactly &a[0], the address of the first integer in the array

a[0]

a[1]

a[2]...

...

&a[0] 1000

&a[1] 1004

&a[2] 1008

1000&a 2160

30

Arrays and Pointers - Examples CConsider the following declarations:

You can use the index [] operator with a pointer:

Indexing can be used with any pointer, but it onlymakes sense when the pointer points to an array

1a

2 3 ? ?int a[5] = {1, 2, 3};

int * p;p

p = &a[2];1

a2 3 ? ?

p

p[0] = 17;p[1] = 23;

1a

2 17 23 ?

p

Page 6: C  tour

6

31

Arrays are NOT Pointers CDeclaring an array sets aside space for its elements

char a[5];

Declaring a pointer variable sets aside only space to hold the variable

char * p;

You can change a pointer variable, but not the addressof an array

char b[6];p = b; // OK

a = b; // ERROR !

a

a[0] a[1] a[2] a[3] a[4]

p

bb[0] b[1] b[2] b[3] b[4]

p

b[5]

32

Other resourcesA very good tutorial on pointers and arrays in C:

http://pw1.netcom.com/%7Etjensen/ptr/pointers.htm