C Fundamentals! C vs. Java: Design Goals. q Java design goals! q Implications for Java! language, machine language, hardware!

Size: px
Start display at page:

Download "C Fundamentals! C vs. Java: Design Goals. q Java design goals! q Implications for Java! language, machine language, hardware!"

Transcription

1 C Fundamentals C vs. Java: Design Goals q Java design goals q Support object-oriented programming q Allow program to be executed on multiple operating systems q Support using computer networks q Execute code from remote sources securely q Adopt the good parts of other languages (esp. C and C++) q Implications for Java q Good for application-level programming q High-level q Virtual machine insulates programmer from underlying assembly language, machine language, hardware q Portability over efficiency q Security over efficiency q Security over flexibility 1

2 C vs. Java: Design Goals q C design goals q Support structured programming q Support development of the Unix OS and Unix tools q As Unix became popular, so did C q Implications for C q Good for system-level programming q q q q q But often used for application-level programming sometimes inappropriately Low-level q Close to assembly language; close to machine language; close to hardware Efficiency over portability Efficiency over security Flexibility over security C vs. Java: Design Goals q Differences in design goals explain many differences between the languages q C s design goal explains many of its eccentricities q We ll see examples throughout the course 2

3 Circle Program q File circle.c: #include <stdio.h> int main(void) /* Read a circle's radius from stdin, and compute and write its diameter and circumference to stdout. Return 0. */ int radius; int diam; double circum; printf("enter the circle's radius:\n"); scanf("%d", &radius); diam = 2 * radius; circum = * (double)diam; printf("a circle with radius %d has diameter %d\n", radius, diam); printf("and circumference %f.\n", circum); return 0; Building and Running q To build (preprocess, compile, assemble, and link): $ gcc circle.c o circle q To run: $./circle Enter the circle's radius: 5 A circle with radius 5 has diameter 10 and circumference Typed by user 3

4 Steps in the Build Process q To build one step at a time: Preprocess: circle.c circle.i Compile: circle.i circle.s Assemble: circle.s circle.o $ gcc E circle.c > circle.i $ gcc S circle.i $ gcc c circle.s $ gcc circle.o o circle Link: circle.o circle q Why build one step at a time? q Helpful for learning how to interpret error messages q Permits partial builds (described later in course) The Preprocessor s View q File circle.c: #include <stdio.h> int main(void) /* Read a circle's radius from stdin, and compute and write its diameter and circumference to stdout. Return 0. */ int radius; int diam; double circum; printf("enter the circle's radius:\n"); scanf("%d", &radius); diam = 2 * radius; circum = * (double)diam; printf("a circle with radius %d has diameter %d\n", radius, diam); printf("and circumference %f.\n", circum); return 0; 4

5 Results of Preprocessing q File circle.i: int printf(char*, ); int scanf(char*, ); int main(void) int radius; int diam; double circum; printf("enter the circle's radius:\n"); scanf("%d", &radius); diam = 2 * radius; circum = * (double)diam; printf("a circle with radius %d has diameter %d\n", radius, diam); printf("and circumference %f.\n", circum); return 0; Where are the DEFINITIONS of printf() and scanf()? What is Wrong? #include <stdio.h> int main() SomeFunction(); return 0; void SomeFunction() printf( My prototype is missing\n ); 5

6 The Compiler s View q File circle.i: int printf(char*, ); int scanf(char*, ); int main(void) int radius; int diam; double circum; printf("enter the circle's radius:\n"); scanf("%d", &radius); diam = 2 * radius; circum = * (double)diam; printf("a circle with radius %d has diameter %d\n", radius, diam); printf("and circumference %f.\n", circum); return 0; The Compiler s View (cont.) q File circle.i: int printf(char*, ); int scanf(char*, ); int main(void) int radius; int diam; double circum; printf("enter the circle's radius:\n"); scanf("%d", &radius); diam = 2 * radius; circum = * (double)diam; printf("a circle with radius %d has diameter %d\n", radius, diam); printf("and circumference %f.\n", circum); return 0; & ( address of ) operator Explained later in course, with pointers 6

7 What is Wrong? #include <stdio.h> int main() int sum; for(int i = 1; i <= 10; i++) sum = sum + i; int fact; for(i = 1; i <= 10; i++) fact = fact * i; return 0; The Compiler s View (cont.) q File circle.i: int printf(char*, ); int scanf(char*, ); int main(void) int radius; int diam; double circum; printf("enter the circle's radius:\n"); scanf("%d", &radius); diam = 2 * radius; circum = * (double)diam; printf("a circle with radius %d has diameter %d\n", radius, diam); printf("and circumference %f.\n", circum); return 0; 7

8 The Compiler s View (cont.) q File circle.i: int printf(char*, ); int scanf(char*, ); int main(void) int radius; int diam; double circum; printf("enter the circle's radius:\n"); scanf("%d", &radius); diam = 2 * radius; circum = * (double)diam; printf("a circle with radius %d has diameter %d\n", radius, diam); printf("and circumference %f.\n", circum); return 0; Results of Compiling q File circle.s:.lc0:.lc1: main:.section.rodata.string "Enter the circle's radius:\n".string "%d".section.text.globl main.type pushl movl pushl call addl subl leal pushl pushl call %ebp %esp, %ebp $.LC0 printf $16, %esp $8, %esp -4(%ebp), %eax %eax $.LC1 scanf Assembly language q Still missing definitions of printf() and scanf() 8

9 Results of Assembling q File circle.o: Listing omitted Not human-readable Machine language q Object file q Still missing definitions of printf() and scanf() The Linker s View q File circle.o: Listing omitted Not human-readable Machine language q The linker: q Observes that q Code in circle.o calls printf() and scanf() q Code in circle.o does not define printf() or scanf() q Fetches machine language definitions of printf() and scanf() from standard C library (/usr/lib/libc.a on your machine) q Merges those definitions with circle.o to create 9

10 Results of Linking q File circle: Listing omitted Not human-readable Machine language q Complete executable binary file Run-Time View q At run-time, memory devoted to program is divided into sections: TEXT RODATA DATA BSS HEAP STACK TEXT (read-only) Stores RODATA (read-only) Stores STACK (read/write) Stores Other sections described later in course 10

11 Run-Time View: Startup q At program startup: TEXT contains machine language code defining main(), printf(), scanf(), etc. TEXT STACK RODATA main printf scanf STACK is empty Enter the circle s radius\n\0 %d\0 RODATA contains every string constant used in program; each is an array of characters, terminated with the null character ( \0 ) A circle with radius %d has diameter %d\n\0 and circumference %f.\n\0 Run-Time View: Declarations int radius; int diam; double circum; TEXT STACK RODATA main printf scanf Enter the circle s radius\n\0 %d\0 A circle with radius %d has diameter %d\n\0 and circumference %f.\n\0 11

12 Run-Time View: Writing a String printf("enter the circle's radius:\n"); TEXT STACK RODATA main printf scanf circum diam radius Enter the circle s radius\n\0 %d\0 A circle with radius %d has diameter %d\n\0 and circumference %f.\n\0 Run-Time View: Reading an int scanf("%d", &radius); TEXT STACK RODATA main printf scanf circum diam radius 5 Enter the circle s radius\n\0 %d\0 A circle with radius %d has diameter %d\n\0 and circumference %f.\n\0 12

13 Run-Time View: Computing Results diam = 2 * radius; circum = * (double)diam; TEXT STACK RODATA main printf scanf circum diam radius 5 Enter the circle s radius\n\0 %d\0 A circle with radius %d has diameter %d\n\0 and circumference %f.\n\0 Run-Time View: Writing an int printf("a circle with radius %d has diameter %d\n", radius, diam); TEXT STACK RODATA main printf scanf circum diam radius Enter the circle s radius\n\0 %d\0 A circle with radius %d has diameter %d\n\0 and circumference %f.\n\0 13

14 Run-Time View: Writing a double printf("and circumference %f.\n", circum); TEXT STACK RODATA main printf scanf circum diam radius Enter the circle s radius\n\0 %d\0 A circle with radius %d has diameter %d\n\0 and circumference %f.\n\0 Run-Time View: Exiting return 0; 14

15 What Goes Where? int fact(n) int i, result=1; for(i = 1; i<=n; i++) result = result * i; return result; int main() int n; printf( Enter a value\n ); scanf( %d, &n); printf( The factorial of %d is %d, n, fact(n)); return 0; What Goes Where? int fact(n) int i, ret=1; for(i = 1; i<=n; i++) ret = ret * i; return ret; TEXT STACK RODATA int main() int n; printf( Enter a value\n ); scanf( %d, &n); printf( The factorial of %d is %d, n,fact(n)); return 0; 15

16 Circle Program q File circle.c: #include <stdio.h> int main(void) /* Read a circle's radius from stdin, and compute and write its diameter and circumference to stdout. Return 0. */ int radius; int diam; double circum; printf("enter the circle's radius:\n"); scanf("%d", &radius); diam = 2 * radius; circum = * (double)diam; printf("a circle with radius %d has diameter %d\n", radius, diam); printf("and circumference %f.\n", circum); return 0; Toward Version 2 q Problem (stylistic flaw): q is a magic number q Should give it a symbolic name to q Increase code clarity q q Solution: Thereby increase code maintainability q (In Java: final fields, final variables) q In C: three approaches 16

17 Symbolic Constants: #define q Approach 1: #define void f(void) #define START_STATE 0 #define POSSIBLE_COMMENT_STATE 1 #define COMMENT_STATE 2... int state;... state = START_STATE;... state = COMMENT_STATE;... Symbolic Constants: #define q Approach 1 strengths q Preprocessor does substitutions only for tokens int mystart_state; /* No replacement */ q Preprocessor does not do substitutions within string constants printf("what is the START_STATE?\n"); /* No replacement */ q Simple textual replacement; works for any type of data #define PI

18 Version 2 using #define #include <stdio.h> int main(void) /* Read a circle's radius from stdin, and compute and write its diameter and circumference to stdout. Return 0. */ int radius; int diam; double circum; printf("enter the circle's radius:\n"); scanf("%d", &radius); diam = 2 * radius; circum = * (double)diam; printf("a circle with radius %d has diameter %d\n", radius, diam); printf("and circumference %f.\n", circum); return 0; Symbolic Constants: #define q Approach 1 weaknesses Preprocessor does not respect context Preprocessor does not respect scope void f(void) #define MAX 1000 int MAX = 2000; void f(void) #define MAX 1000 void g(void) int MAX = 2000; Conventions: Use all uppercase for constants -- and only for constants Place #defines at beginning of file, not within function definitions 18

19 Symbolic Constants: const q Approach 2: constant variables (oxymoron) void f(void) const int START_STATE = 0; const int POSSIBLE_COMMENT_STATE = 1; const int COMMENT_STATE = 2; int state;... state = START_STATE;... state = COMMENT_STATE;... Version 2 using const #include <stdio.h> int main(void) /* Read a circle's radius from stdin, and compute and write its diameter and circumference to stdout. Return 0. */ int radius; int diam; double circum; printf("enter the circle's radius:\n"); scanf("%d", &radius); diam = 2 * radius; circum = * (double)diam; printf("a circle with radius %d has diameter %d\n", radius, diam); printf("and circumference %f.\n", circum); return 0; 19

20 Symbolic Constants: const q Approach 2 strengths q Works for any type of data const double PI = ; q Handled by compiler, not preprocessor; compiler respects context and scope q Approach 2 weaknesses q Does not work for array lengths (unlike C++) const int ARRAY_LENGTH = 10;... int a[array_length]; /* Compiletime error */ Symbolic Constants: enum q Approach 3: Enumerations void f(void) enum State START_STATE, POSSIBLE_COMMENT_STATE, COMMENT_STATE,...; enum State state;... state = START_STATE;... state = COMMENT_STATE;... 20

21 Symbolic Constants: enum q Approach 3 note q Enumerated constants are interchangeable with ints q START_STATE is the same as 0 q POSSIBLE_COMMENT_STATE is the same as 1 q Etc. state = 0; /* Can assign int to enum. */ i = START_STATE; /* Can assign enum to int. */ Symbolic Constants: enum q Approach 3 strengths q Can explicitly specify values for names enum State START_STATE = 5, POSSIBLE_COMMENT_STATE = 3, COMMENT_STATE = 4,...; q Can omit type name, thus effectively giving names to int literals enum MAX_VALUE = 9999;... int i = MAX_VALUE; q Works when specifying array lengths enum ARRAY_LENGTH = 10;... int a[array_length];... 21

22 Version 2 using enum #include <stdio.h> int main(void) /* Read a circle's radius from stdin, and compute and write its diameter and circumference to stdout. Return 0. */ int radius; int diam; double circum; printf("enter the circle's radius:\n"); scanf("%d", &radius); diam = 2 * radius; circum = * (double)diam; printf("a circle with radius %d has diameter %d\n", radius, diam); printf("and circumference %f.\n", circum); return 0; Symbolic Constants: enum q Approach 3 weakness q Does not work for non-integral data types enum PI = ; /* Compiletime error */ 22

23 Symbolic Constant Style Rules q Summary of style rules: 1. Use enumerations to give symbolic names to integral constants 2. Use const variables to give symbolic names to non-integral constants 3. Use #define with all uppercase at beginning of file Toward Version 3 q Problem: q Program does not handle bad user input $ circle Enter the circle's radius: abc User enters a non-number. How can the program detect that? What should the program do? 23

24 Detecting Bad User Input q Solution Part 1: Detecting bad user input scanf("%d", &radius) q q scanf() returns number of values successfully read Solution: Reporting Failure to User q Solution Part 2: Reporting failure to the user Stream Default Binding stdin Purpose Normal input C Functions stdout stderr Normal output Abnormal output q To report failure to user, should write a message to stderr 24

25 Reporting Failure to OS q Solution Part 3: Reporting failure to the operating system Nature of Program Completion Status Code that Program Should Return to OS Successful 0 EXIT_SUCCESS (#defined in stdlib.h as 0) Unsuccessful EXIT_FAILURE (#defined in stdlib.h as???) q To generate status code x, program should: q Execute return x statement to return from main() function, or q Call exit(x) to abort program System-dependent; q Shell can examine status code on tanner, 1 q Note: q In main() function, return statement and exit() function have same effect q In other functions, they have different effects What is Wrong? #include <stdio.h> int main() int n; printf( Enter a value\n ); scanf( %d, &n); printf( The factorial of %d is %d, n,fact(n)); return EXIT_SUCCESS; q Compilation error: q EXIT_SUCCESS' undeclared (first use in this function) 25

26 Circle Program (Version 3) #include <stdio.h> int main(void) /* Read a circle's radius from stdin, and compute and write its diameter and circumference to stdout. Return 0 if successful. */ const double PI = ; int radius, diam; double circum; printf("enter the circle's radius:\n"); /* Read radius here */ diam = 2 * radius; circum = PI * (double)diam; printf("a circle with radius %d has diameter %d\n", radius, diam); printf("and circumference %f.\n", circum); return 0; Arrays in C 26

27 Array Declaration q 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 Array Initialization #define MAX 5 int count[max] = 5, 7, 2, 4, 8; count [0] [1] [2] [3] [4] q Providing too many initial values causes a compile-time error: int count[max] = 1,2,3,4,5,6; // ERROR q 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; 27

28 Array Indices q Logically, valid indices for an array range from 0 to MAX-1, where MAX is the dimension of the array int A[6]; stands for A[0], A[1], A[2], A[3], A[4] and A[5] Logically, there is no A[6] q Memory A[0] A[1] A[2] A[3] A[4] A[5] Out-of-Bounds Array Indices q A common logical error in processing arrays is exceeding the valid index range: #define MAX 100 int somearray[max]; somearray[max] = 0; // will compile // but run time ERROR q What happens when a statement uses an array index that is out of bounds? int i; for(i = 0; i <= MAX; i++) somearray[i] = 0; No automatic checking of array indices at run time 28

29 Out-of-Bounds Array Indices q The 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. q Most operating systems, such as Windows NT and Unix, will detect that a memory access violation has occurred and suspend or kill your program NO Aggregate Array Operations q Aggregate operations refer to operations on an array as a whole, as opposed to operations on individual array elements. #define MAX 100 int x[max]; int y[max]; q 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 29

30 Strings in C String Declarations q Unlike Java, there is no String data type in C q 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 // or char msg[ ] = Hey ; // no \0 memory for 6 characters ( 5 plus the null char \0 ) automatically allocated 30

31 Memory Representation q char some[10]; [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] q char msg[6] = H, e, y,,, \0 ; [0] [1] [2] [3] [4] [5] H e y 0 q char msg[8] = Hey ; [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] H e y 0 q char msg[] = Hey ; [0] [1] [2] [3] [4] [5] H e y 0 Reading Into a String (1) #define MAX_BUFFER 20 char buffer[max_buffer]; scanf( %s, buffer); gets(buffer); // or q What if the array is not large enough to hold the input? q characters will be stored into memory locations past the end of the array q will result in run-time memory access violation error 31

32 Reading Into a String (2) q Better: #define MAX_BUFFER 20 char buffer[max_buffer]; fgets(buffer, MAX_BUFFER, stdin); q fgets is similar to gets, but: q it takes a third argument, in our case standard input q if stores into buffer no more than MAX_BUFFER chars (extra characters are ignored), so memory violation error won t occur Functions for Manipulating Strings q C 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 Unix manual pages to find out what this function does 32

33 String exercise q Write a function int length(char * s); that returns the length of the string argument. Examples: length( abc ) should return 3 length( abc\0 ) should return length( abc\\0 ) should return Pointers in C 33

34 What are Pointers? q A pointer is a variable that holds the ADDRESS of another variable q Suppose that we have an integer variable int i; and wish to have a pointer point to this variable. q How do we know where i is located? &i is the address of i. The operator & is called the ADDRESS-OF operator. Pointers and Addresses q We can declare that a pointer iptr points to an int by saying int * iptr; q Suppose that we have: int i = 5; int j = 7; (&i) 100 (&j) i j iptr q 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. iptr i 5 34

35 Declaring Pointers q When declaring several pointer variables in one statement - the asterisk does not distribute throughout the statement: int *p, q; equivalent to int * p; int q; equivalent to int * p, * q; int * p; int * q; Initializing Pointers q We can also initialize iptr at the point of declaration: int i; int * iptr = &i; iptr i??? q Here is a common error: int i; int * iptr = i; // ERROR: i is not an address 35

36 Dereference * q The value of the data being pointed at is obtained by using the operator * q 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. Dereference Example int i; int * p = &i; *p = 101; (*p)++; i??? p i??? p i 101 p i 102 Equivalent to i = 101; Equivalent to i++; q A dereferenced pointer behaves exactly like the variable it points to. 36

37 Note the Difference Assume: ptr1 i 5 ptr1 ptr2 i j 5 7 After ptr1 = ptr2; ptr2 j 7 ptr1 i 7 After ptr2 j 7 *ptr1 = *ptr2; Uninitialized Pointers q Suppose that we have the following declarations: int i; int * iptr; *iptr = 100; iptr q What is the value of iptr? Undefined. What could happen? q iptr could hold an address that does not make sense at all, causing your program to crash if dereferenced. i??? q 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. 37

38 Putting it all Together... int i, value; int * iptr; // declares iptr to be a pointer to an integer i = 510; /* Step 1 */ iptr = &i; /* Step 2 */ value = *iptr; /* Step 3 */ iptr i value After Step1: After Step2: iptr i value After Step3: iptr i value The null Pointer q The value of a pointer can be: q some garbage (pointer unassigned) q the address of some variable (eg., int * p = &i; ) q 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. q The null pointer is a special pointer value that a program can test for: if (somepointer == 0)... 38

39 Arrays vs. Pointers Arrays and Pointers - Examples q Consider the following declarations: int a[5] = 1, 2, 3; a 1 2 3?? int * p; p p = &a[2]; a 1 2 3?? p q You can use the index [] operator with a pointer: p[0] = 17; p[1] = 23; a ? Indexing can be used with any pointer, but it only makes sense when the pointer points to an array. p 39

40 Arrays are NOT Pointers q Declaring an array sets aside space for its elements char a[5]; a a[0] a[1] a[2] a[3] a[4] q Declaring a pointer variable sets aside only space to hold the variable char * p; p q You can change a pointer variable, but not the address of an array char b[6]; p = b; // OK p b = p; // ERROR b b[0] b[1] b[2] b[3] b[4] b[5] Indexing Pointers int a[5]; int *p, *q; p a p = a; p[1]= 44; q q = p + 2; q[-1] = 43; q[2] = 46; 40

41 Pointer Arithmetic int a[5]; p a Subscript: a[i] means *(a+i) int *p; 4 bytes p = a + 2; Note: arithmetic scales by data size (e.g., int of 4 bytes) Quaint usage of pointer arithmetic Add up the elements of an array: More straightforwardly: int a[100]; int sum, *p; int a[100];... int sum, i; for (p=a; p<a+100; p++)... sum += *p; for (i=0; i<100; i++) sum += a[i]; 41

42 Array Parameters to Functions void printarray(int *p, int n) int i; for (i=0; i<n; i++) printf( %d\n,p[i]); int fib[5] = 1, 1, 2, 3, 5; int main(void) printarray(fib, 5); Array Params Pointer Params void printarray(int *p, int n)... void printarray(int p[5], int n)... void printarray(int p[ ], int n)... void printarray(int p[1000], int n)... int main(void) printarray(fib, 5); All these declarations are equivalent Try them out. 42

43 Exercise: Reverse Array q Reverse the values in an array q Inputs: integer array a, and number of elements n q Output: values of a stored in reverse order q Algorithm q Swap the first and last elements in the array q Swap the second and second-to-last elements q Exercise: length using pointers q Rewrite the function int length(char * s); using pointers, instead of array indices. Examples: length( abc ) should return 3 length( abc\0 ) should return length( abc\\0 ) should return 43

44 Swapping two values q Write a function void swap(int first, int second); that swaps the values of its arguments. Example: int i1 = 11, i2 = 22; printf( Before: i1=%d, i2=%d\n, i1, i2); swap(i1, i2); printf( After: i1=%d, i2=%d\n, i1, i2); Output should be: Before: i1=11, i2=22 After: i1=22, i2=11 Can t do it? q Try the correct version void swap(int *first, int *second); that swaps the values of its arguments. Example: int i1 = 11, i2 = 22; printf( Before: i1=%d, i2=%d\n, i1, i2); swap(&i1, &i2); printf( After: i1=%d, i2=%d\n, i1, i2); Output should be: Before: i1=11, i2=22 After: i1=22, i2=11 44

45 Summary q Simple C programs q Program structure q Detecting and reporting failure q Functionality of the gcc command q Preprocessor, compiler, assembler, linker q Memory layout of a Unix process q TEXT, RODATA, STACK sections q Input/Output in C q printf, scanf, fprintf, getchar, putchar, gets, fgets q Arrays, Strings and Pointers in C 45

Program Building. Goals for this Lecture. Help you learn about: Program structure. Detecting and reporting failure

Program Building. Goals for this Lecture. Help you learn about: Program structure. Detecting and reporting failure Simple C Program Building 1 Goals for this Lecture Help you learn about: Simple C programs Program structure Defining symbolic constants Detecting and reporting failure Functionality of the gcc command

More information

CSC 2400: Computing Systems

CSC 2400: Computing Systems CSC 2400: Computing Systems Professor Mirela Damian http://www.csc.villanova.edu/~mdamian/ 1 Introductions Mirela Damian (professor) Room 167A in the Mendel Science Building mirela.damian@villanova.edu

More information

Towards the Hardware"

Towards the Hardware CSC 2400: Computer Systems Towards the Hardware Chapter 2 Towards the Hardware High-level language (Java) High-level language (C) assembly language machine language (IA-32) 1 High-Level Language Make programming

More information

CSC 2400: Computer Systems. Arrays and Strings in C

CSC 2400: Computer Systems. Arrays and Strings in C CSC 2400: Computer Systems Arrays and Strings in C Lecture Overview Arrays! List of elements of the same type Strings! Array of characters ending in \0! Functions for manipulating strings 1 Arrays: C vs.

More information

CSC 2400: Computer Systems. Arrays and Strings in C

CSC 2400: Computer Systems. Arrays and Strings in C CSC 2400: Computer Systems Arrays and Strings in C Lecture Overview Arrays! List of elements of the same type Strings! Array of characters ending in \0! Functions for manipulating strings 1 Arrays in C

More information

Goals of this Lecture

Goals of this Lecture A Taste of C C 1 Goals of this Lecture Help you learn about: The basics of C Deterministic finite state automata (DFA) Expectations for programming assignments Why? Help you get started with Assignment

More information

CSC 1600 Memory Layout for Unix Processes"

CSC 1600 Memory Layout for Unix Processes CSC 16 Memory Layout for Unix Processes" 1 Lecture Goals" Behind the scenes of running a program" Code, executable, and process" Memory layout for UNIX processes, and relationship to C" : code and constant

More information

Variables, Pointers, and Arrays

Variables, Pointers, and Arrays Variables, Pointers, and Arrays Prof. David August COS 217 http://www.cs.princeton.edu/courses/archive/fall06/cos217/ 1 Overview of Today s Lecture Pointers o Differences between value, variable, and pointer

More information

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ...

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ... Why Pointers Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation. They provide support for dynamic data structures, such

More information

Lectures 5-6: Introduction to C

Lectures 5-6: Introduction to C Lectures 5-6: Introduction to C Motivation: C is both a high and a low-level language Very useful for systems programming Faster than Java This intro assumes knowledge of Java Focus is on differences Most

More information

Lectures 5-6: Introduction to C

Lectures 5-6: Introduction to C Lectures 5-6: Introduction to C Motivation: C is both a high and a low-level language Very useful for systems programming Faster than Java This intro assumes knowledge of Java Focus is on differences Most

More information

Princeton University Computer Science 217: Introduction to Programming Systems. Goals of this Lecture. A Taste of C. Agenda.

Princeton University Computer Science 217: Introduction to Programming Systems. Goals of this Lecture. A Taste of C. Agenda. Princeton University Computer Science 217: Introduction to Programming Systems Goals of this Lecture A Taste of C C Help you learn about: The basics of C Deterministic finite-state automata (DFA) Expectations

More information

Assembly Language Programming - III

Assembly Language Programming - III Assembly Language Programming - III GDB Debugger Please refer to the handout New GDB commands (power.s) info registers (prints all register values) print/d $eax (prints individual register value. Note

More information

(2) Accidentally using the wrong instance of a variable (sometimes very hard one to find).

(2) Accidentally using the wrong instance of a variable (sometimes very hard one to find). Scope and storage class of variables The scope of a variable refers to those portions of a program wherein it may be accessed. Failure to understand scoping rules can lead to two problems: (1) Syntax errors

More information

ch = argv[i][++j]; /* why does ++j but j++ does not? */

ch = argv[i][++j]; /* why does ++j but j++ does not? */ CMPS 12M Introduction to Data Structures Lab Lab Assignment 4 The purpose of this lab assignment is to get more practice programming in C, including the character functions in the library ctype.h, and

More information

C Compilation Model. Comp-206 : Introduction to Software Systems Lecture 9. Alexandre Denault Computer Science McGill University Fall 2006

C Compilation Model. Comp-206 : Introduction to Software Systems Lecture 9. Alexandre Denault Computer Science McGill University Fall 2006 C Compilation Model Comp-206 : Introduction to Software Systems Lecture 9 Alexandre Denault Computer Science McGill University Fall 2006 Midterm Date: Thursday, October 19th, 2006 Time: from 16h00 to 17h30

More information

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor CS 261 Fall 2017 Mike Lam, Professor C Introduction Variables, Memory Model, Pointers, and Debugging The C Language Systems language originally developed for Unix Imperative, compiled language with static

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

Question 4.2 2: (Solution, p 5) Suppose that the HYMN CPU begins with the following in memory. addr data (translation) LOAD 11110

Question 4.2 2: (Solution, p 5) Suppose that the HYMN CPU begins with the following in memory. addr data (translation) LOAD 11110 Questions 1 Question 4.1 1: (Solution, p 5) Define the fetch-execute cycle as it relates to a computer processing a program. Your definition should describe the primary purpose of each phase. Question

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

are all acceptable. With the right compiler flags, Java/C++ style comments are also acceptable.

are all acceptable. With the right compiler flags, Java/C++ style comments are also acceptable. CMPS 12M Introduction to Data Structures Lab Lab Assignment 3 The purpose of this lab assignment is to introduce the C programming language, including standard input-output functions, command line arguments,

More information

Copyright The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Copyright The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 18 I/O in C Standard C Library I/O commands are not included as part of the C language. Instead, they are part of the Standard C Library. A collection of functions and macros that must be implemented

More information

Running a C program Compilation Python and C Variables and types Data and addresses Functions Performance. John Edgar 2

Running a C program Compilation Python and C Variables and types Data and addresses Functions Performance. John Edgar 2 CMPT 125 Running a C program Compilation Python and C Variables and types Data and addresses Functions Performance John Edgar 2 Edit or write your program Using a text editor like gedit Save program with

More information

Lecture 2: C Programming Basic

Lecture 2: C Programming Basic ECE342 Introduction to Embedded Systems Lecture 2: C Programming Basic Ying Tang Electrical and Computer Engineering Rowan University 1 Facts about C C was developed in 1972 in order to write the UNIX

More information

Pointers, Dynamic Data, and Reference Types

Pointers, Dynamic Data, and Reference Types Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation The new operator The delete operator Dynamic Memory Allocation for Arrays 1 C++ Data Types simple

More information

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community http://csc.cs.rit.edu History and Evolution of Programming Languages 1. Explain the relationship between machine

More information

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011 CS 61C: Great Ideas in Computer Architecture (Machine Structures) Introduction to C (Part II) Instructors: Randy H. Katz David A. Patterson http://inst.eecs.berkeley.edu/~cs61c/sp11 Spring 2011 -- Lecture

More information

BSM540 Basics of C Language

BSM540 Basics of C Language BSM540 Basics of C Language Chapter 4: Character strings & formatted I/O Prof. Manar Mohaisen Department of EEC Engineering Review of the Precedent Lecture To explain the input/output functions printf()

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 9 Pointer Department of Computer Engineering 1/46 Outline Defining and using Pointers

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 3 Constants, Variables, Data Types, And Operations Department of Computer Engineering

More information

Arrays Arrays and pointers Loops and performance Array comparison Strings. John Edgar 2

Arrays Arrays and pointers Loops and performance Array comparison Strings. John Edgar 2 CMPT 125 Arrays Arrays and pointers Loops and performance Array comparison Strings John Edgar 2 Python a sequence of data access elements with [index] index from [0] to [len-1] dynamic length heterogeneous

More information

Memory and C/C++ modules

Memory and C/C++ modules Memory and C/C++ modules From Reading #5 and mostly #6 More OOP topics (templates; libraries) as time permits later Program building l Have: source code human readable instructions l Need: machine language

More information

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language 1 History C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC

More information

Draft. Chapter 1 Program Structure. 1.1 Introduction. 1.2 The 0s and the 1s. 1.3 Bits and Bytes. 1.4 Representation of Numbers in Memory

Draft. Chapter 1 Program Structure. 1.1 Introduction. 1.2 The 0s and the 1s. 1.3 Bits and Bytes. 1.4 Representation of Numbers in Memory Chapter 1 Program Structure In the beginning there were 0s and 1s. GRR 1.1 Introduction In this chapter we will talk about memory: bits, bytes and how data is represented in the computer. We will also

More information

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36 Department of Computer Science College of Engineering Boise State University August 25, 2017 1/36 Pointers and Arrays A pointer is a variable that stores the address of another variable. Pointers are similar

More information

Arrays and Strings. Antonio Carzaniga. February 23, Faculty of Informatics Università della Svizzera italiana Antonio Carzaniga

Arrays and Strings. Antonio Carzaniga. February 23, Faculty of Informatics Università della Svizzera italiana Antonio Carzaniga Arrays and Strings Antonio Carzaniga Faculty of Informatics Università della Svizzera italiana February 23, 2015 Outline General memory model Definition and use of pointers Invalid pointers and common

More information

SWEN-250 Personal SE. Introduction to C

SWEN-250 Personal SE. Introduction to C SWEN-250 Personal SE Introduction to C A Bit of History Developed in the early to mid 70s Dennis Ritchie as a systems programming language. Adopted by Ken Thompson to write Unix on a the PDP-11. At the

More information

A Fast Review of C Essentials Part I

A Fast Review of C Essentials Part I A Fast Review of C Essentials Part I Structural Programming by Z. Cihan TAYSI Outline Program development C Essentials Functions Variables & constants Names Formatting Comments Preprocessor Data types

More information

C-LANGUAGE CURRICULAM

C-LANGUAGE CURRICULAM C-LANGUAGE CURRICULAM Duration: 2 Months. 1. Introducing C 1.1 History of C Origin Standardization C-Based Languages 1.2 Strengths and Weaknesses Of C Strengths Weaknesses Effective Use of C 2. C Fundamentals

More information

Princeton University Computer Science 217: Introduction to Programming Systems. A Taste of C

Princeton University Computer Science 217: Introduction to Programming Systems. A Taste of C Princeton University Computer Science 217: Introduction to Programming Systems A Taste of C C 1 Goals of this Lecture Help you learn about: The basics of C Deterministic finite-state automata (DFA) Expectations

More information

Design and development of embedded systems for the Internet of Things (IoT) Fabio Angeletti Fabrizio Gattuso

Design and development of embedded systems for the Internet of Things (IoT) Fabio Angeletti Fabrizio Gattuso Design and development of embedded systems for the Internet of Things (IoT) Fabio Angeletti Fabrizio Gattuso Why C? Test on 21 Android Devices with 32-bits and 64-bits processors and different versions

More information

Part V. Memory and pointers. Philip Blakely (LSC) C++ Introduction 145 / 370

Part V. Memory and pointers. Philip Blakely (LSC) C++ Introduction 145 / 370 Part V and pointers Philip Blakely (LSC) C++ Introduction 145 / 370 Outline 19 20 Function pointers 21 Global variables Philip Blakely (LSC) C++ Introduction 146 / 370 Heap and Stack The stack is a Last-In-First-Out

More information

Topic 8: I/O. Reading: Chapter 7 in Kernighan & Ritchie more details in Appendix B (optional) even more details in GNU C Library manual (optional)

Topic 8: I/O. Reading: Chapter 7 in Kernighan & Ritchie more details in Appendix B (optional) even more details in GNU C Library manual (optional) Topic 8: I/O Reading: Chapter 7 in Kernighan & Ritchie more details in Appendix B (optional) even more details in GNU C Library manual (optional) No C language primitives for I/O; all done via function

More information

CS 261 Fall Mike Lam, Professor. Structs and I/O

CS 261 Fall Mike Lam, Professor. Structs and I/O CS 261 Fall 2018 Mike Lam, Professor Structs and I/O Typedefs A typedef is a way to create a new type name Basically a synonym for another type Useful for shortening long types or providing more meaningful

More information

CSCI 171 Chapter Outlines

CSCI 171 Chapter Outlines Contents CSCI 171 Chapter 1 Overview... 2 CSCI 171 Chapter 2 Programming Components... 3 CSCI 171 Chapter 3 (Sections 1 4) Selection Structures... 5 CSCI 171 Chapter 3 (Sections 5 & 6) Iteration Structures

More information

C Introduction. Comparison w/ Java, Memory Model, and Pointers

C Introduction. Comparison w/ Java, Memory Model, and Pointers CS 261 Fall 2018 Mike Lam, Professor C Introduction Comparison w/ Java, Memory Model, and Pointers Please go to socrative.com on your phone or laptop, choose student login and join room LAMJMU The C Language

More information

Procedural programming with C

Procedural programming with C Procedural programming with C Dr. C. Constantinides Department of Computer Science and Software Engineering Concordia University Montreal, Canada August 11, 2016 1 / 77 Functions Similarly to its mathematical

More information

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ. C BOOTCAMP DAY 2 CS3600, Northeastern University Slides adapted from Anandha Gopalan s CS132 course at Univ. of Pittsburgh Pointers 2 Pointers Pointers are an address in memory Includes variable addresses,

More information

Arrays and Pointers in C. Alan L. Cox

Arrays and Pointers in C. Alan L. Cox Arrays and Pointers in C Alan L. Cox alc@rice.edu Objectives Be able to use arrays, pointers, and strings in C programs Be able to explain the representation of these data types at the machine level, including

More information

Lecture 03 Bits, Bytes and Data Types

Lecture 03 Bits, Bytes and Data Types Lecture 03 Bits, Bytes and Data Types Computer Languages A computer language is a language that is used to communicate with a machine. Like all languages, computer languages have syntax (form) and semantics

More information

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files CS113: Lecture 7 Topics: The C Preprocessor I/O, Streams, Files 1 Remember the name: Pre-processor Most commonly used features: #include, #define. Think of the preprocessor as processing the file so as

More information

An Ungentle Introduction to C

An Ungentle Introduction to C Warum C? - Sicherheit auf allen Systemschichten Applikationen Hilfssysteme BS-Werkzeuge BS-Kern HW Evtl. Hochsprachen Skripte C Assembler - je tiefer die kompromittierte Schicht, umso größer der Schaden

More information

A. Year / Module Semester Subject Topic 2016 / V 2 PCD Pointers, Preprocessors, DS

A. Year / Module Semester Subject Topic 2016 / V 2 PCD Pointers, Preprocessors, DS Syllabus: Pointers and Preprocessors: Pointers and address, pointers and functions (call by reference) arguments, pointers and arrays, address arithmetic, character pointer and functions, pointers to pointer,initialization

More information

Applied Programming and Computer Science, DD2325/appcs15 PODF, Programmering och datalogi för fysiker, DA7011

Applied Programming and Computer Science, DD2325/appcs15 PODF, Programmering och datalogi för fysiker, DA7011 Applied Programming and Computer Science, DD2325/appcs15 PODF, Programmering och datalogi för fysiker, DA7011 Autumn 2015 Lecture 3, Simple C programming M. Eriksson (with contributions from A. Maki and

More information

Intel assembly language using gcc

Intel assembly language using gcc QOTD Intel assembly language using gcc Assembly language programming is difficult. Make no mistake about that. It is not for wimps and weaklings. - Tanenbaum s 6th, page 519 These notes are a supplement

More information

Pointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017

Pointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017 Pointers (part 1) EECS 2031 25 September 2017 1 What are pointers? We have seen pointers before. scanf( %f, &inches );! 2 1 Example char c; c = getchar(); printf( %c, c); char c; char *p; c = getchar();

More information

C Programming Review CSC 4320/6320

C Programming Review CSC 4320/6320 C Programming Review CSC 4320/6320 Overview Introduction C program Structure Keywords & C Types Input & Output Arrays Functions Pointers Structures LinkedList Dynamic Memory Allocation Macro Compile &

More information

Outline. Computer programming. Debugging. What is it. Debugging. Hints. Debugging

Outline. Computer programming. Debugging. What is it. Debugging. Hints. Debugging Outline Computer programming Debugging Hints Gathering evidence Common C errors "Education is a progressive discovery of our own ignorance." Will Durant T.U. Cluj-Napoca - Computer Programming - lecture

More information

Pointers. Pointer Variables. Chapter 11. Pointer Variables. Pointer Variables. Pointer Variables. Declaring Pointer Variables

Pointers. Pointer Variables. Chapter 11. Pointer Variables. Pointer Variables. Pointer Variables. Declaring Pointer Variables Chapter 11 Pointers The first step in understanding pointers is visualizing what they represent at the machine level. In most modern computers, main memory is divided into bytes, with each byte capable

More information

CMPSC 311- Introduction to Systems Programming Module: Introduction to C

CMPSC 311- Introduction to Systems Programming Module: Introduction to C CMPSC 311- Introduction to Systems Programming Module: Introduction to C Professor Patrick McDaniel Fall 2015 Building HW1 You are provided with a Makefile that will assist in making your program. You

More information

DECLARAING AND INITIALIZING POINTERS

DECLARAING AND INITIALIZING POINTERS DECLARAING AND INITIALIZING POINTERS Passing arguments Call by Address Introduction to Pointers Within the computer s memory, every stored data item occupies one or more contiguous memory cells (i.e.,

More information

o Code, executable, and process o Main memory vs. virtual memory

o Code, executable, and process o Main memory vs. virtual memory Goals for Today s Lecture Memory Allocation Prof. David August COS 217 Behind the scenes of running a program o Code, executable, and process o Main memory vs. virtual memory Memory layout for UNIX processes,

More information

Contents. A Review of C language. Visual C Visual C++ 6.0

Contents. A Review of C language. Visual C Visual C++ 6.0 A Review of C language C++ Object Oriented Programming Pei-yih Ting NTOU CS Modified from www.cse.cuhk.edu.hk/~csc2520/tuto/csc2520_tuto01.ppt 1 2 3 4 5 6 7 8 9 10 Double click 11 12 Compile a single source

More information

Language comparison. C has pointers. Java has references. C++ has pointers and references

Language comparison. C has pointers. Java has references. C++ has pointers and references Pointers CSE 2451 Language comparison C has pointers Java has references C++ has pointers and references Pointers Values of variables are stored in memory, at a particular location A location is identified

More information

Computer Science 217 Final Exam May 15, :30pm-4:30pm

Computer Science 217 Final Exam May 15, :30pm-4:30pm NAME: Login name: Computer Science 217 Final Exam May 15, 2009 1:30pm-4:30pm This test has eight (8) questions and thirteen (13) pages. Put your name (or login-id) on every page, and write out and sign

More information

Summary of Last Class. Processes. C vs. Java. C vs. Java (cont.) C vs. Java (cont.) Tevfik Ko!ar. CSC Systems Programming Fall 2008

Summary of Last Class. Processes. C vs. Java. C vs. Java (cont.) C vs. Java (cont.) Tevfik Ko!ar. CSC Systems Programming Fall 2008 CSC 4304 - Systems Programming Fall 2008 Lecture - II Basics of C Programming Summary of Last Class Basics of UNIX: logging in, changing password text editing with vi, emacs and pico file and director

More information

3/22/2016. Pointer Basics. What is a pointer? C Language III. CMSC 313 Sections 01, 02. pointer = memory address + type

3/22/2016. Pointer Basics. What is a pointer? C Language III. CMSC 313 Sections 01, 02. pointer = memory address + type Pointer Basics What is a pointer? pointer = memory address + type C Language III CMSC 313 Sections 01, 02 A pointer can contain the memory address of any variable type A primitive (int, char, float) An

More information

Introduction to C. Robert Escriva. Cornell CS 4411, August 30, Geared toward programmers

Introduction to C. Robert Escriva. Cornell CS 4411, August 30, Geared toward programmers Introduction to C Geared toward programmers Robert Escriva Slide heritage: Alin Dobra Niranjan Nagarajan Owen Arden Cornell CS 4411, August 30, 2010 1 Why C? 2 A Quick Example 3 Programmer s Responsibilities

More information

10/20/2015. Midterm Topic Review. Pointer Basics. C Language III. CMSC 313 Sections 01, 02. Adapted from Richard Chang, CMSC 313 Spring 2013

10/20/2015. Midterm Topic Review. Pointer Basics. C Language III. CMSC 313 Sections 01, 02. Adapted from Richard Chang, CMSC 313 Spring 2013 Midterm Topic Review Pointer Basics C Language III CMSC 313 Sections 01, 02 1 What is a pointer? Why Pointers? Pointer Caution pointer = memory address + type A pointer can contain the memory address of

More information

Object-Oriented Programming

Object-Oriented Programming iuliana@cs.ubbcluj.ro Babes-Bolyai University 2018 Overview 1 2 3 4 5 6 7 I No beard, no belly, no guru... Ken Thompson (B), Dennis Ritchie (C) - UNIX Bjarne Stroustrup (C++) James Gosling (Java) Figure:

More information

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018 Pointer Basics Lecture 13 COP 3014 Spring 2018 March 28, 2018 What is a Pointer? A pointer is a variable that stores a memory address. Pointers are used to store the addresses of other variables or memory

More information

printf( Please enter another number: ); scanf( %d, &num2);

printf( Please enter another number: ); scanf( %d, &num2); CIT 593 Intro to Computer Systems Lecture #13 (11/1/12) Now that we've looked at how an assembly language program runs on a computer, we're ready to move up a level and start working with more powerful

More information

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Arrays and Pointers. CSE 2031 Fall November 11, 2013 Arrays and Pointers CSE 2031 Fall 2013 November 11, 2013 1 Arrays l Grouping of data of the same type. l Loops commonly used for manipulation. l Programmers set array sizes explicitly. 2 Arrays: Example

More information

C: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21

C: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21 Department of Computer Science College of Engineering Boise State University September 11, 2017 1/21 Pointers A pointer is a variable that stores the address of another variable. Pointers are similar to

More information

CIT Week13 Lecture

CIT Week13 Lecture CIT 3136 - Week13 Lecture Runtime Environments During execution, allocation must be maintained by the generated code that is compatible with the scope and lifetime rules of the language. Typically there

More information

Output of sample program: Size of a short is 2 Size of a int is 4 Size of a double is 8

Output of sample program: Size of a short is 2 Size of a int is 4 Size of a double is 8 Pointers Variables vs. Pointers: A variable in a program is something with a name and a value that can vary. The way the compiler and linker handles this is that it assigns a specific block of memory within

More information

CS164: Programming Assignment 5 Decaf Semantic Analysis and Code Generation

CS164: Programming Assignment 5 Decaf Semantic Analysis and Code Generation CS164: Programming Assignment 5 Decaf Semantic Analysis and Code Generation Assigned: Sunday, November 14, 2004 Due: Thursday, Dec 9, 2004, at 11:59pm No solution will be accepted after Sunday, Dec 12,

More information

Arrays, Strings, & Pointers

Arrays, Strings, & Pointers Arrays, Strings, & Pointers Alexander Nelson August 31, 2018 University of Arkansas - Department of Computer Science and Computer Engineering Arrays, Strings, & Pointers Arrays, Strings, & Pointers are

More information

CPEG421/621 Tutorial

CPEG421/621 Tutorial CPEG421/621 Tutorial Compiler data representation system call interface calling convention Assembler object file format object code model Linker program initialization exception handling relocation model

More information

From Java to C. Thanks to Randal E. Bryant and David R. O'Hallaron (Carnegie-Mellon University) for providing the basis for these slides

From Java to C. Thanks to Randal E. Bryant and David R. O'Hallaron (Carnegie-Mellon University) for providing the basis for these slides From Java to C Thanks to Randal E. Bryant and David R. O'Hallaron (Carnegie-Mellon University) for providing the basis for these slides 1 Outline Overview comparison of C and Java Good evening Preprocessor

More information

Lecture 2: C Programm

Lecture 2: C Programm 0 3 E CS 1 Lecture 2: C Programm ing C Programming Procedural thought process No built in object abstractions data separate from methods/functions Low memory overhead compared to Java No overhead of classes

More information

Outline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C

Outline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C Lecture 1 C primer What we will cover A crash course in the basics of C You should read the K&R C book for lots more details Various details will be exemplified later in the course Outline Overview comparison

More information

Lecture07: Strings, Variable Scope, Memory Model 4/8/2013

Lecture07: Strings, Variable Scope, Memory Model 4/8/2013 Lecture07: Strings, Variable Scope, Memory Model 4/8/2013 Slides modified from Yin Lou, Cornell CS2022: Introduction to C 1 Outline Review pointers New: Strings New: Variable Scope (global vs. local variables)

More information

Lecture 16. Daily Puzzle. Functions II they re back and they re not happy. If it is raining at midnight - will we have sunny weather in 72 hours?

Lecture 16. Daily Puzzle. Functions II they re back and they re not happy. If it is raining at midnight - will we have sunny weather in 72 hours? Lecture 16 Functions II they re back and they re not happy Daily Puzzle If it is raining at midnight - will we have sunny weather in 72 hours? function prototypes For the sake of logical clarity, the main()

More information

Laboratory 2: Programming Basics and Variables. Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information

Laboratory 2: Programming Basics and Variables. Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information Laboratory 2: Programming Basics and Variables Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information 3. Comment: a. name your program with extension.c b. use o option to specify

More information

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT C Review MaxMSP Developers Workshop Summer 2009 CNMAT C Syntax Program control (loops, branches): Function calls Math: +, -, *, /, ++, -- Variables, types, structures, assignment Pointers and memory (***

More information

Computer Programming Unit v

Computer Programming Unit v READING AND WRITING CHARACTERS We can read and write a character on screen using printf() and scanf() function but this is not applicable in all situations. In C programming language some function are

More information

Standard File Pointers

Standard File Pointers 1 Programming in C Standard File Pointers Assigned to console unless redirected Standard input = stdin Used by scan function Can be redirected: cmd < input-file Standard output = stdout Used by printf

More information

Lab 3. Pointers Programming Lab (Using C) XU Silei

Lab 3. Pointers Programming Lab (Using C) XU Silei Lab 3. Pointers Programming Lab (Using C) XU Silei slxu@cse.cuhk.edu.hk Outline What is Pointer Memory Address & Pointers How to use Pointers Pointers Assignments Call-by-Value & Call-by-Address Functions

More information

United States Naval Academy Electrical and Computer Engineering Department EC310-6 Week Midterm Spring AY2017

United States Naval Academy Electrical and Computer Engineering Department EC310-6 Week Midterm Spring AY2017 United States Naval Academy Electrical and Computer Engineering Department EC310-6 Week Midterm Spring AY2017 1. Do a page check: you should have 8 pages including this cover sheet. 2. You have 50 minutes

More information

Goals of this Lecture

Goals of this Lecture C Pointers Goals of this Lecture Help you learn about: Pointers and application Pointer variables Operators & relation to arrays 2 Pointer Variables The first step in understanding pointers is visualizing

More information

CSC209H Lecture 3. Dan Zingaro. January 21, 2015

CSC209H Lecture 3. Dan Zingaro. January 21, 2015 CSC209H Lecture 3 Dan Zingaro January 21, 2015 Streams (King 22.1) Stream: source of input or destination for output We access a stream through a file pointer (FILE *) Three streams are available without

More information

25.2 Opening and Closing a File

25.2 Opening and Closing a File Lecture 32 p.1 Faculty of Computer Science, Dalhousie University CSCI 2132 Software Development Lecture 32: Dynamically Allocated Arrays 26-Nov-2018 Location: Chemistry 125 Time: 12:35 13:25 Instructor:

More information

BLM2031 Structured Programming. Zeyneb KURT

BLM2031 Structured Programming. Zeyneb KURT BLM2031 Structured Programming Zeyneb KURT 1 Contact Contact info office : D-219 e-mail zeynebkurt@gmail.com, zeyneb@ce.yildiz.edu.tr When to contact e-mail first, take an appointment What to expect help

More information

Computers Programming Course 5. Iulian Năstac

Computers Programming Course 5. Iulian Năstac Computers Programming Course 5 Iulian Năstac Recap from previous course Classification of the programming languages High level (Ada, Pascal, Fortran, etc.) programming languages with strong abstraction

More information

Processes. Johan Montelius KTH

Processes. Johan Montelius KTH Processes Johan Montelius KTH 2017 1 / 47 A process What is a process?... a computation a program i.e. a sequence of operations a set of data structures a set of registers means to interact with other

More information

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014. Arrays Arrays and Pointers l Grouping of data of the same type. l Loops commonly used for manipulation. l Programmers set array sizes explicitly. EECS 2031 Fall 2014 November 11, 2013 1 2 Arrays: Example

More information

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology Introduction to C++ Massachusetts Institute of Technology ocw.mit.edu 6.096 Pointers 1 Background 1.1 Variables and Memory When you declare a variable, the computer associates the variable name with a

More information

CSE 374 Programming Concepts & Tools

CSE 374 Programming Concepts & Tools CSE 374 Programming Concepts & Tools Hal Perkins Fall 2017 Lecture 8 C: Miscellanea Control, Declarations, Preprocessor, printf/scanf 1 The story so far The low-level execution model of a process (one

More information

C++ for Java Programmers

C++ for Java Programmers Basics all Finished! Everything we have covered so far: Lecture 5 Operators Variables Arrays Null Terminated Strings Structs Functions 1 2 45 mins of pure fun Introduction Today: Pointers Pointers Even

More information