C tour

702 views

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
702
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
11
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

C tour

  1. 1. Data Types C char short int Tour of C long float double Data Types, Arrays, Strings and Pointers in C long double signed/ unsigned – char, short, int, long 1 2Like Java, Like C C Operators same as in Java - Arithmetic int i = i+1; i++; i--; i*=2; +, -, *, /, % - Relational and logical Arrays in C <, >, <=, >=, ==, != &&, ||, &, |, ! Syntax same as in Java - if() { } else { } - while() { } - do { } while (); - for(i = 1; i <= 100; i++) { } - switch() {case 1: …} - continue; break; 3 4Array Declaration C Array Initialization C The dimension must be a constant or a constant #define MAX 5 count expression (needs to be determined at compile time) int count[MAX] = {5, 7, 2, 4, 8}; 5 7 2 4 8 [0] [1] [2] [3] [4] #define BUFFSIZE 256 #define MAXSIZE 12 int main() Providing too many initial values causes a compile-time { error: int size = 6; int count[MAX] = {1,2,3,4,5,6}; // ERROR! char buffer[BUFFERSIZE]; // elegant declaration // constant integer dimension If the number of initial values listed is less than the char buffer[256]; // NOT an elegant declaration capacity of the array, the remaining elements are // integer literal dimension automatically initialized to 0. Thus int dice[BUFFSIZE / 2]; // constant integer expression // used for dimension int count[5] = {2}; float rollValue[size]; // NOT valid - size is not a is equivalent to int count[5] = {2,0,0,0,0}; // constant ... 5 6
  2. 2. Array Indices C Out-of-Bounds Array Indices (1) C Logically, valid indices for an array range from 0 to A common logical error in processing arrays is MAX-1, where MAX is the dimension of the array exceeding the valid index range: #define MAX 100 int A[6]; int someArray[MAX]; stands for A[0], A[1], A[2], A[3], A[4] and A[5] someArray[MAX] = 0; // will compile // but run time ERROR ! Logically, there is no A[6]! What happens when a statement uses an array index Memory that is out of bounds? int i; No automatic checking of A[0] A[1] A[2] A[3] A[4] A[5] for(i = 0; i <= MAX; i++) array indices at run time ! someArray[i] = 0; 7 8Out-of-Bounds Array Indices (2) C Lack of Aggregate Array Operations C The memory location someArray[100] may : Aggregate operations refer to operations on an array as a whole, as opposed to operations on individual 1. Store a variable declared in your program – that array elements. variable will be altered. Since there is no statement that directly assigns a value to that variable, this #define MAX 100 effect seems very mysterious when debugging. int x[MAX]; 2. Not be allocated for the use of your program. The int y[MAX]; result depends on the operating system you are using Some operating systems, such as Windows95/98 do not There are no aggregate operations on arrays: carefully monitor memory accesses and your program may corrupt a value that actually belongs to another program Assignment x = y; Error ! Other operating systems, such as Windows NT and Unix, Comparison if (x == y) … Error! will detect that a memory access violation has occurred I/O printf(“%d”, x); Error! and suspend or kill your program Arithmetic: x = x + y; Error! 9 10 String Declarations C Unlike Java, there is no String data type in C Strings in C are simply arrays of characters terminated with 0 (character ‘0’) Strings in C 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’ // or char msg[ ] = “Hey !”; // no ‘0’ memory for 6 characters ( 5 plus the null char ‘0’ ) automatically allocated 11 12
  3. 3. Memory Representation Reading Into a String (1) C char some[10]; #define MAX_BUFFER 20 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] char buffer[MAX_BUFFER]; scanf(“%s”, buffer); // or char msg[6] = {‘H’,‘e’,‘y’,‘ ’,‘!’,‘0’}; gets(buffer, MAX_BUFFER); [0] [1] [2] [3] [4] [5] ‘H’‘e’‘y’‘ ’‘!’ 0 What if the array is not large enough to hold the char msg[8] = “Hey !”; input? [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] - characters will be stored into memory locations past ‘H’‘e’‘y’‘ ’‘!’ 0 the end of the array char msg[] = “Hey !”; - will result in run-time memory access violation error ! [0] [1] [2] [3] [4] [5] ‘H’‘e’‘y’‘ ’‘!’ 0 13 14Reading Into a String (2) C Functions for Manipulating Strings C Better: C provides a large number of functions for #define MAX_BUFFER 20 manipulating strings. Four important ones: char buffer[MAX_BUFFER]; strlen(s) // returns the length of s fgets(buffer, MAX_BUFFER, stdin); strcpy(toS, fromS) // copy fromS to toS (toS must be large enough) fgets is similar to gets, but: strcmp(s1, s2) - it takes a third argument, in our case standard input // returns 0 if s1 == s2 // returns an integer < 0 if s1 < s2 - if stores into buffer no more than MAX_BUFFER chars // returns an integer > 0 if s1 > s2 (extra characters are ignored), so memory violation error won’t occur strtok – read the Sun manual pages to find out what this function does 15 16 What are Pointers? C A pointer is a variable that holds the address of another variable (object) Suppose that we have an integer variable Pointers in C int 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. 17 18
  4. 4. Pointers Made Easy (1) C Pointers Made Easy (2) C We can declare that a pointer iPtr points to an int We can also initialize iPtr at the point of by saying declaration: int * iPtr; (&i) 100 5 i int i; iPtr i ??? ... int * iPtr = &i; Suppose that we have: (&j) 180 7 j int i = 5; Here is a common error: ... int j = 7; 260 100 iPtr int i; We can make iPtr point to i by assigning to iPtr the int * iPtr = i; // ERROR: i is not an address memory location where i is stored. Thus iPtr = &i; iPtr i sets iPtr to point to i. 5 19 20Declaring Pointers C Dereference * C When declaring several pointer variables in one The value of the data being pointed at is obtained by statement - the asterisk does not distribute using the operator * throughout the statement: If p is a pointer value, then equivalent to int * p; *p int *p, q; int q; refers to the variable pointed to by p. Since equivalent to int * p; int * p, * q; int * q; reference is another name for address, the operator * is called dereference operator. 21 22Dereference Example C Note the Difference … C int i; int * p = &i; *p = 101; (*p)++; ptr1 i ptr1 i ptr1 i 5 5 7 i p i p i p i ??? ??? 101 102 ptr2 j ptr2 j ptr2 j 7 7 7 Equivalent to Equivalent to i = 101; i++; Initial state After After ptr1 = ptr2; *ptr1 = *ptr2; starting from initial starting from initial state state• A dereferenced pointer behaves exactly like the variable it points to. 23 24
  5. 5. Uninitialized Pointers C Putting it all Together... C Suppose that we have the following declarations: … with the help of a simple example: int i, value; int i; iPtr i int * iPtr; // declares iPtr to be a pointer to an integer int * iPtr; ??? *iPtr = 100; i = 510; // Step 1 iPtr = &i; // Step 2 value = *iPtr; // Step 3 What is the value of iPtr? Undefined. What could happen? iPtr i value - iPtr could hold an address that does not make sense at all, Step 1 ??? 510 ??? causing your program to crash if dereferenced. iPtr i value - iPtr could point to an address which is accessible. Then the Step 2 assignment *iPtr = 100; would accidentally change some 510 ??? other data, which could result in a crash at a later point. This is a tough error to detect since the cause and symptom Step 3 iPtr i value may be widely separated in time. 510 510 25 26The null Pointer C The 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; Arrays and Pointers 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) ... 27 28Arrays and Pointers C Arrays and Pointers - Examples C An array name is basically a constant pointer Consider the following declarations: a int a[5] = {1, 2, 3}; 1 2 3 ? ? ... Consider the declaration: &a[0] 1000 a[0] p &a[1] 1004 a[1] int * p; char a[3]; &a[2] 1008 a[2] ... a p = &a[2]; &a 2160 1000 1 2 3 ? ? p 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. You can use the index [] operator with a pointer: a p[0] = 17; 1 2 17 23 ? p[1] = 23; The value of a is exactly &a[0], the address of the p Indexing can be used with any pointer, but it only first integer in the array makes sense when the pointer points to an array 29 30
  6. 6. Arrays are NOT Pointers C Other resources Declaring an array sets aside space for its elements A very good tutorial on pointers and arrays in C: char a[5]; a a[0] a[1] a[2] a[3] a[4] http://pw1.netcom.com/%7Etjensen/ptr/pointers.htm Declaring a pointer variable sets aside only space to hold the variable char * p; p You can change a pointer variable, but not the address of an array b b[0] b[1] b[2] b[3] b[4] b[5] char b[6]; p p = b; // OK a = b; // ERROR ! 31 32

×