c fundamentals - villanova university › ... › notes › 02_cfundamentals.pdf · 1 c...

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

Upload: others

Post on 27-Jun-2020

27 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

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!

Page 2: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

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  But often used for application-level programming –

sometimes inappropriately!q  Low-level!

q  Close to assembly language; close to machine language; close to hardware!

q  Efficiency over portability!q  Efficiency over security!q  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!

Page 3: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

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 = 3.14159 * (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):!

q  To run:!$ gcc circle.c –o circle

$ ./circle

Enter the circle's radius:

5

A circle with radius 5 has diameter 10

and circumference 31.415900.

Typed by!user!

Page 4: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

4

Steps in the Build Process!q  To build one step at a time:!

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)!

$ gcc –E circle.c > circle.i

$ gcc –S circle.i

$ gcc –c circle.s

$ gcc circle.o –o circle

Preprocess:!circle.c → circle.i!

Compile:!circle.i → circle.s!

Assemble:!circle.s → circle.o!

Link:!circle.o → circle!

q  File circle.c:!

The Preprocessor’s View!

#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 = 3.14159 * (double)diam; printf("A circle with radius %d has diameter %d\n", radius, diam); printf("and circumference %f.\n", circum); return 0; }

Page 5: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

5

q  File circle.i:!

Results of Preprocessing!

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 = 3.14159 * (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”); }

Page 6: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

6

q  File circle.i:!

The Compiler’s View!

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 = 3.14159 * (double)diam; printf("A circle with radius %d has diameter %d\n", radius, diam); printf("and circumference %f.\n", circum); return 0; }

q  File circle.i:!

The Compiler’s View (cont.)!

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 = 3.14159 * (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!

Page 7: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

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; }

q  File circle.i:!

The Compiler’s View (cont.)!

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 = 3.14159 * (double)diam; printf("A circle with radius %d has diameter %d\n", radius, diam); printf("and circumference %f.\n", circum); return 0; }

Page 8: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

8

q  File circle.i:!

The Compiler’s View (cont.)!

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 = 3.14159 * (double)diam; printf("A circle with radius %d has diameter %d\n", radius, diam); printf("and circumference %f.\n", circum); return 0; }

q  File circle.s:!

q  Still missing definitions of printf() and scanf()!

Results of Compiling!

Assembly language!

.section .rodata .LC0: .string "Enter the circle's radius:\n" .LC1: .string "%d" … .section .text .globl main .type main, @function main: pushl %ebp movl %esp, %ebp … pushl $.LC0 call printf addl $16, %esp subl $8, %esp leal -4(%ebp), %eax pushl %eax pushl $.LC1 call scanf …

Page 9: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

9

q  File circle.o:!

q  Object file!q  Still missing definitions of printf() and scanf()!

Results of Assembling!

Machine language!Listing omitted

Not human-readable

q  File circle.o:!

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…!

The Linker’s View!

Machine language!Listing omitted

Not human-readable

Page 10: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

10

q  File circle:!

q  Complete executable binary file!

Results of Linking!

Listing omitted

Not human-readable Machine language!

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!

Page 11: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

11

Run-Time View: Startup!q  At program startup:!

TEXT! STACK! RODATA!Enter the circle’s radius\n\0!

%d\0!

A circle with radius %d has diameter %d\n\0!

and circumference %f.\n\0 !

RODATA contains!every string constant used !in program; each is an array!of characters, terminated with!the null character (‘\0’)!

STACK is!empty!

------!

!!!

------!

main!

printf!

scanf!

TEXT contains!machine language!code defining main(),!printf(), scanf(), etc.!

Run-Time View: Declarations!

TEXT! STACK! RODATA!Enter the circle’s radius\n\0!

%d\0!

A circle with radius %d has diameter %d\n\0!

and circumference %f.\n\0 !

int radius; int diam; double circum;

------!

!!!

------!

main!

printf!

scanf!

Page 12: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

12

Run-Time View: Writing a String!

TEXT! STACK! RODATA!Enter the circle’s radius\n\0!

%d\0!

A circle with radius %d has diameter %d\n\0!

and circumference %f.\n\0 !

printf("Enter the circle's radius:\n");

radius!diam!

circum!

------!

!!!

------!

main!

printf!

scanf!

Run-Time View: Reading an int!

TEXT! STACK! RODATA!Enter the circle’s radius\n\0!

%d\0!

A circle with radius %d has diameter %d\n\0!

and circumference %f.\n\0 !

scanf("%d", &radius);

5!radius!diam!

circum!

------!

!!!

------!

main!

printf!

scanf!

Page 13: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

13

Run-Time View: Computing Results!

TEXT! STACK! RODATA!Enter the circle’s radius\n\0!

%d\0!

A circle with radius %d has diameter %d\n\0!

and circumference %f.\n\0 !

diam = 2 * radius; circum = 3.14159 * (double)diam;

5!

radius!diam!

circum!

------!

!!!

------!

main!

printf!

scanf!

Run-Time View: Writing an int!

TEXT! STACK! RODATA!Enter the circle’s radius\n\0!

%d\0!

A circle with radius %d has diameter %d\n\0!

and circumference %f.\n\0 !

printf("A circle with radius %d has diameter %d\n", radius, diam);

5!

10!

31.4159

radius!diam!

circum!

------!

!!!

------!

main!

printf!

scanf!

Page 14: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

14

Run-Time View: Writing a double!

TEXT! STACK! RODATA!Enter the circle’s radius\n\0!

%d\0!

A circle with radius %d has diameter %d\n\0!

and circumference %f.\n\0 !

printf("and circumference %f.\n", circum);

5!

10!

31.4159

radius!diam!

circum!

------!

!!!

------!

main!

printf!

scanf!

Run-Time View: Exiting!return 0;

Page 15: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

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?!

TEXT! STACK! RODATA!

int fact(n) { int i, ret=1; for(i = 1; i<=n; i++) ret = ret * i; return ret; }

int main() { int n; printf(“Enter a value\n”); scanf(“%d”, &n); printf(“The factorial of %d is %d”, n,fact(n)); return 0; }

Page 16: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

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 = 3.14159 * (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  3.14159 is a “magic number”!q  Should give it a symbolic name to!

q  Increase code clarity!q  Thereby increase code maintainability!

q  Solution:!q  (In Java: final fields, final variables)!q  In C: three approaches…!

!

Page 17: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

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!

q  Preprocessor does not do substitutions within string constants!

!

q  Simple textual replacement; works for any type of data!

int mySTART_STATE; /* No replacement */

printf("What is the START_STATE?\n"); /* No replacement */

#define PI 3.14159

Page 18: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

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; }

q  Approach 1 weaknesses!

Symbolic Constants: #define!

void f(void) { #define MAX 1000 … } void g(void) { { int MAX = 2000; … }

void f(void) { #define MAX 1000 … int MAX = 2000; }

•  Preprocessor does notrespect scope!

•  Preprocessor does notrespect context!

•  Conventions:!•  Use all uppercase for constants -- and only for constants!•  Place #defines at beginning of file, not within function definitions!

Page 19: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

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; }

Page 20: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

20

Symbolic Constants: const!q  Approach 2 strengths!

q  Works for any type of data!

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 double PI = 3.14159;

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; ... }

Page 21: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

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!

q  Can omit type name, thus effectively giving names to int literals!

q  Works when specifying array lengths!

enum State {START_STATE = 5, POSSIBLE_COMMENT_STATE = 3, COMMENT_STATE = 4, ...};

enum {MAX_VALUE = 9999}; ... int i = MAX_VALUE;

enum {ARRAY_LENGTH = 10}; ... int a[ARRAY_LENGTH]; ...

Page 22: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

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 = 3.14159}; /* Compiletime error */

Page 23: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

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?!

Page 24: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

24

Detecting Bad User Input!q  Solution Part 1: Detecting bad user input!

q  scanf() returns number of values successfully read!q  Solution:!

scanf("%d", &radius)

Reporting Failure to User!q  Solution Part 2: Reporting failure to the user!

q  To report failure to user, should write a message to stderr!!

Stream! Default Binding!

Purpose! C Functions!

stdin! “Normal” input!

stdout! “Normal” output!

stderr! “Abnormal” output!

Page 25: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

25

Reporting Failure to OS!q  Solution Part 3: Reporting failure to the operating system!

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!

q  Shell can examine status code!q  Note:!

q  In main() function, return statement and exit() function have same effect!q  In other functions, they have different effects!

Nature of Program Completion!

Status Code that ProgramShould Return to OS!

Successful! 0 EXIT_SUCCESS (#defined in stdlib.h as 0)!

Unsuccessful! EXIT_FAILURE (#defined in stdlib.h as ???)!

System-dependent;!on tanner, 1!

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)!

Page 26: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

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 = 3.14159; 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!

Page 27: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

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

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};

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

[0] [1] [2]

count

[3] [4]

7 2 4 8 5

Page 28: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

28

Array Indices q  Logically, valid indices for an array range from 0 to MAX-1,

where MAX is the dimension of the array!

q  Memory!

int A[6]; stands for A[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]

Out-of-Bounds Array Indices q  A common logical error in processing arrays is exceeding

the valid index range:!

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

#define MAX 100 int 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 !!

Page 29: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

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 !!

Page 30: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

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!

Page 31: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

31

Memory Representation q  char some[10];

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

q  char msg[8] = “Hey !”;

q  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]

Reading Into a String (1) #define MAX_BUFFER 20 char buffer[MAX_BUFFER]; scanf(“%s”, buffer); // or gets(buffer);

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 ! !

Page 32: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

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!

Page 33: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

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 !

Page 34: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

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;!

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.

5

7

100

...

...

(&i) 100

(&j) 180

260

i

j

iPtr

5 iPtr i

Page 35: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

35

Declaring Pointers q  When 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!

Initializing Pointers q  We can also initialize iPtr at the point of declaration:!

int i; int * iPtr = &i;

q  Here is a common error:!!int i; int * iPtr = i; // ERROR: i is not an address!

??? iPtr i

Page 36: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

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 !

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

!

p ??? i

??? i

int * p = &i;

p 101 i

*p = 101;

p 102 i

(*p)++; int i;

Equivalent to i = 101;

Equivalent to i++;

Page 37: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

37

Note the Difference …

ptr1 5

i

ptr2 7

j

Assume:!

ptr1 5

i

ptr2 7

j After !

ptr1 = ptr2;

ptr1 7

i

ptr2 7

j

After !

*ptr1 = *ptr2; !

Uninitialized Pointers q  Suppose that we have the following declarations:!

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

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.!

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.!

???

iPtr i

Page 38: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

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 */

i value iPtr

i value iPtr

i value iPtr

After Step1:

After Step2:

After Step3:

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) ...

Page 39: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

39

Arrays vs. Pointers !

q  Consider the following declarations:!

q  You can use the index [] operator with a pointer:! !!! !Indexing can be used with any pointer, but it only! !makes sense when the pointer points to an array.!

Arrays and Pointers - Examples

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

int * p; p

p = &a[2]; 1 a 2 3 ? ?

p

p[0] = 17; p[1] = 23; 1 a 2 17 23 ?

p

Page 40: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

40

Arrays are NOT Pointers q  Declaring an array sets aside space for its elements!

char a[5];

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

char * p;

q  You can change a pointer variable, but not the address of an array!

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

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

p

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

p b[5]

Indexing Pointers int a[5]; int *p, *q;

!

217

226

a

q

p[1]= 44;

!

44 p

p = a;

!

q = p + 2;

!

q[-1] = 43;

!

45 44 43

46

q[2] = 46; !

Page 41: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

41

Pointer Arithmetic int a[5];

!

217

226

a p

Subscript: a[i] “means” *(a+i)

int *p;

p = a + 2;

Note: arithmetic scales by data size (e.g., int of 4 bytes)

4 bytes

Quaint usage of pointer arithmetic Add up the elements of an array:!!! int a[100];! int sum, *p;! ...! for (p=a; p<a+100; p++) ! sum += *p;! !!

More straightforwardly:!!

int a[100];! int sum, i;! ...! for (i=0; i<100; i++) ! sum += a[i];!

!!

Page 42: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

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.

Page 43: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

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  …!

77 31 94 5 186

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 !_____!

Page 44: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

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!

Page 45: C Fundamentals - Villanova University › ... › notes › 02_CFundamentals.pdf · 1 C Fundamentals! C vs. Java: Design Goals ! Java design goals!! Support object-oriented programming!!

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!