Computer Systems: Cynthia Lee
Computer Systems: Cynthia Lee
CS107
Cynthia Lee
Todays Topics
NEXT LECTURE:
C addresses, pointer arithmetic, strings
Its ok to feel like this right now when it comes to Unix. Well continue to
work on that while we introduce C.
C++
Java
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
printf()
// like System.out.print() or cout
printf("Hello, world!");
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[]
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)
Passing an Array to a
Function
(CODE DEMO)
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
55
12
Memory
Memory
addresses
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)
x:
y:
p:
q: