Вы находитесь на странице: 1из 24

Computer Systems

CS107

Cynthia Lee

Todays Topics

Your first C program, your first command-line compilation


Pointers and arrays

Review from CS106B/X, building to a more intense level


More on files and strings

fopen, fclose, getc, strcpy, strstr, strcat

NEXT LECTURE:
C addresses, pointer arithmetic, strings

For today (optional):


If you have a laptop with you (totally optional), you may want to open a
browser tab to https://ideone.com/
This will allow you to type along with me as we write our first C
program

C Programming: Getting Started

Its ok to feel like this right now when it comes to Unix. Well continue to
work on that while we introduce C.

History and background of C


Birthdate around 1970
Created to make writing Unix (the OS itself) and tools for Unix easier
Part of the C/C++/Java family of languages
(with C++ and Java coming later)
Design principles:
Small, simple abstractions of hardware
Minimalist aesthetic
C is much more concerned with efficiency and minimalism than safety
(Java) or convenient high-level services and abstractions (Java, C++)

C++

Java

Comparison of C, Java, C++


Some things will be very familiar:
Syntax
Basic data types
Arithmetic, relational, and logical operators
You may be sad about whats missing:
No power features of C++ (overloading operators, default arguments,
pass by reference, classes/objects, fancy ADTs)
Thin standard libraries (no graphics, networking, etc)
Weak compiler checks, almost no runtime checks
Benefits:
Small language footprint (not much to learn)
Philosophical difference:
Procedural (C)
Procedural + Objects (C++)
Object-Oriented (Java)
6

Things to watch for in our live coding of hello.c:

Unix command to compile (make)


Makefile
C runtime errors (segmentation fault)
printf
scanf
format codes (%s, %d, %f)
making global constant with #define
argc, argv
CTRL-C to kill something in Unix

strings
Unlike C++, there is no string class (no classes at all in C!)
Can be declared as
char * str
char str[30]
These are sort of interchangeablewe will learn what is different in next
lecture
Some useful string functions:
strcat(str1, str2)
// concat str2 to the end of str1
strcmp(str1, str2)
// returns 0 if strings are equal,
// otherwise -1 or 1, for < or >
strdup(str)
// returns a new (malloced) copy of str
strcpy(str1, str2)
// copies contents of str2 to str1
strlen(str)
// finds the length of a str
strstr(str1, str2)
// returns a ptr to the first occurrence
// of str2 in str1
8

Strings code example


We coded this in codestepbystep.com. This version of the solution illustrated
some principles that youll need for assign1, and three of our string functions,
but it has some more work that needs to be done.
Specifically, we need to address the fact that it only works for input strings of
length < 100.
We also need to generalize to use our input i (number of times to repeat)
Well talk about that in the next lecture!
char * repeat(char * str, int i) {
char bigstring[300];
strcpy(bigstring, str);
strcat(bigstring, str);
strcat(bigstring, str);
return strdup(bigstring);
}
9

printf()
// like System.out.print() or cout
printf("Hello, world!");

// like System.out.println() or cout << << endl


printf("Hello, world!\n");

10

Escape sequence

Meaning

\n

Newline

\\

\ (single backslash)

\t

Tab

scanf()
char name[10];
int age, height;
printf("Enter your first name, age, and height: ");
scanf("%s %d %d", name, &age, &height);
printf("Name: %s\tAge:%d\tHeight:%d\n", name, age, height);

Pattern

Use

Type of variable

%d

Integer

int

%c

A single character

char

%f, %lf

Non-integer number

float, double

%s

Whitespace-separated string

char * or char[]

Basic anatomy of main()


int main(int argc, char * argv[])
{
// stuff
return 0;
}

Return value always int (just return 0 all the time and otherwise ignore it)
argc is the size of the argv array
argv array is a collection of the arguments that are typed on the command line in
Unix when you run the program (captured as strings)

The 0th argument is the name of the command itself


Args 1 and on are the arguments

Passing an Array to a
Function
(CODE DEMO)

Starter code (needs work)


#include <stdio.h>
#include <stdlib.h>
double sum(double arr[])
{
double total = 0;
/* loop over array and sum */
return total;
}

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


{
double arr[] = {1.1, 2.2, 3.3, 4.4};
double total = 0.0;
/* want to call sum to calculate total of array values */
total = sum(arr);
printf("Sum = %g\n", total);
return 0;

Key points from the code example:


#include <stdio.h>
#include <stdlib.h>
double sum(double arr[], int length)
{
double total = 0.o;
for (int i=0; i<length; i++)
total += arr[i];
return total;
}

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


{
double arr[] = {1.1, 2.2, 3.3, 4.4};
double total = 0.0;

double arr[] and double *arr are


equivalent for parameter types
Not quite true for local
variable declarations
Any time we pass an array ([] or
* notation), we need to also
pass along its accompanying
array size
Theyre always a pair
Example: argc to go with
argv!

/* want to call sum to calculate total of array values */


total = sum(arr, 4);
printf("Sum = %g\n", total);
return 0;

Pointers!
CULTURE FACT: IN CODE, ITS NOT CONSIDERED RUDE TO
POINT.

Pointers in C
Pointers are fundamental to almost everything in C
Well spend the quarter understanding why
Partly has to do with memory addresses being so
fundamental to assembly, and C being a very thin layer
between you and assembly

Why do we need pointers? What are they good for?


Pointers shine in times when you want to share data structures between
different components of your code
Imagine looking inside a program for managing student and class
information at Stanford
But not Axess because //shudder//
Each student has a bulky record including vital stats, history, etc.
Classes point to each enrolled student, not have own bulky copy

Why do we need pointers? What are they good for?


Pointers shine in times when you want to have flexibility for on-the-fly
changes to the data youre storing
Grow and shrink collection size dynamically
Insert and remove elements into an ordered structure without needing
a ton of reshuffling (think link list or tree structures)
Pointers shine in times when you want to have data lifespan not so
closely tied to function call/return
Allocate something in a function, but keep it when the function returns
(this last reason will make more sense when we talk more about stack vs
heap on Friday)

Pointers and memory


addresses
SOME EXAMPLES

Memory addresses: 106B/X review


When you declare a variable, it is necessarily stored
somewhere in memory
You can ask for any variable's memory address with the
& operator (address-of)
int x = 12;
0x28F620
int *p = &x;
Memory addresses are usually written as hexadecimal
(base-16 or hex) numbers
Ex: 0x28F620
Prefix 0x is a visual cue that this is a hex number
(not really part of the number)

55

12

Memory
Memory
addresses

Memory addresses: some examples


int main(int argc, char *argv[]) {
int x = 12;
int *p = &x;
printf("%d\n", x);
printf("%p\n", p);
What do the last two lines do?
(answer separately for each line)
Compiler warning or error
Runtime error or crash
Prints 12 twice
Prints 12 and something else
Prints something else

0x28F630
0x28F62C

0x28F628
0x28F624

0x28F620

0x4
0x0

Dereference operator *
Note this is a different use of * from the type declaration
int x = 5;
int *p = &x;
// p has type "pointer to int"
printf("%d\n", *p); // dereferencing p
* ONLY works on variables that are pointer types
Unlike address-of &, which works on any variable
Follows the pointer to the destination for a read or write
of that value
(in this class we call that value the pointee, but thats
not an official term)

Memory addresses: some examples


int main(int argc, char *argv[]) {
int x = 5;
int y = 7;
int *p = &x
int *q = &y;
Do these lines of code do the same thing?
*p = y;
p = &y;
A. YES!
B. NO!
C. I dont know!!

x:

y:

p:
q:

Вам также может понравиться