CSE 333
Section 1
Gitlab, Pointers, and C Strings
1
If you haven’t yet, please clone your exercise git repo to your local machine!
Logistics
2
Introductions
3
TA Intro: FILL IN HOWEVER YOU WOULD LIKE!
4
Icebreaker!
Please turn to the people next to you and share:
5
Computing Setup for 333: DEMO
6
CSE Linux Environment
7
Text Editor of Choice
8
Gitlab Repositories
9
git Tagging Demo/Follow-Along
10
Git Repo Usage
11
Pointers in C
12
Pointers
13
Pointer Syntax and Semantics
14
int* ar = (int*) malloc(3*sizeof(int)); // reference
int* p = &ar[1]; // iterator
*p = 3;
0x1b126b0
0x1b126b4
?
3
?
ar
p
Stack
Heap
Output Parameters
15
Output Parameter Example
int temp_sum = 0, temp_product = 1; // initializations
}
16
for (int i = 0; i < len; i++) { // compute product & sum
temp_sum += ar[i];
temp_product *= ar[i];
}
*sum = temp_sum; // set output params
*product = temp_product;
Exercise 1
17
void Division(int numerator,
int denominator,
int* quotient,
int* remainder) {
*quotient = numerator / denominator;
*remainder = numerator % denominator;
}
int main(int argc, char* argv[]) {
int quot, rem;
Division(22, 5, _____, _____);
printf("%d rem %d\n", _____, _____);
return EXIT_SUCCESS;
}
Exercise 2
18
C-Strings
19
C-Strings
20
char str_name[size];
Initialization Examples
21
// list initialization
char str1[6] = {'H','e','l','l','o','\0'};
// string literal initialization
char str2[6] = "Hello";
index | 0 | 1 | 2 | 3 | 4 | 5 |
value | 'H' | 'e' | 'l' | 'l' | 'o' | '\0' |
Common String Literal Error (1/2)
22
index | 0 | 1 | 2 | 3 | 4 | 5 |
value | 'H' | 'e' | 'l' | 'l' | 'o' | '\0' |
// pointer instead of an array
char* str3 = "Hello";
0x402037
str3
Common String Literal Error (2/2)
23
index | 0 | 1 | 2 | 3 | 4 | 5 |
value | 'H' | 'e' | 'l' | 'l' | 'o' | '\0' |
// pointer instead of an array
char* str3 = "Hello";
0x402037
str3
Segfault!
Extra: Exercise 3
void Bar(char ch) {
ch = '3';
}
int main(int argc, char* argv[]) {
char fav_class[] = "CSE331";
Bar(fav_class[5]);
printf("%s\n", fav_class); // should print "CSE333"
return EXIT_SUCCESS;
}
24
Extra: Exercise 4
char* strcpy(char* dest, char* src) {
}
25
Function Pointers
26
int one() { return 1; }
int two() { return 2; }
int three() { return 3; }
int get(int (*func_name)()) {
return func_name();
}
int main(int argc, char* argv[]) {
int res1 = get(one);
int res2 = get(two);
int res3 = get(three);
printf("%d, %d, %d\n", res1, res2, res3);
return EXIT_SUCCESS;
}