lecutre 05
这一讲中讲字符串的指针讲得很好Lecture05.pdflive_session.cmemory.cmemory_errors.cverify_password.cverify_password_soln.c
Side note: use strlen to get the length of a string. Don’t use sizeof!


Arrays of string







We create strings as char[], pass them around as char *

Q: Is there a way to check in code whether a string’s characters are modifiable?
A: No. This is something you can only tell by looking at the code itself and how the string was created.
Q: So then if I am writing a string function that modifies a string, how can I tell if the string passed in is modifiable?
A: You can’t! This is something you instead state as an assumption in your function documentation. If someone calls your function with a read-only string, it will crash, but that’s not your function’s fault :-)
一些程序例子
字符数组的负索引
#include <stdio.h>#include <string.h>void func(char *str) {str[0] = 'S';str++;*str = 'u';str = str + 3;str[-2] = 'm';}int main(int argc, const char *argv[]) {char buf[] = "Monday";printf("before func: %s\n", buf);func(buf);printf("after func: %s\n", buf);return 0;}
输出
,表明str[-2]是在当前str的位置向左查找了2个字符位置,从a到了m的位置。
char* vs char[] exercises
Bonus: Tricky addresses
void tricky_addresses() {char buf[] = "Local";char *ptr1 = buf;char **double_ptr = &ptr1;printf("double_ptr value: %p\n", double_ptr);printf("buf's address: %p\n", &buf);printf("ptr1's value: %s\n", ptr1);printf("ptr1’s deref: %c\n", *ptr1);printf("ptr1’s address: %p\n", &ptr1);printf("ptr1's value address: %p\n", ptr1);char *ptr2 = &buf;printf("ptr2's value: %s\n", ptr2);printf("ptr2’s deref: %c\n", *ptr2);printf("ptr2’s address: %p\n", &ptr2);printf("ptr2's value address: %p\n", ptr2);}
lecture 06
这一讲很好Lecture06.pdflive_session.cskip_spaces.cskip_spaces_soln.c
Pointers & C Parameters
Pointers Summary
• If you are performing an operation with some input and do not care about any changes to the input, pass the data type itself.
• If you are modifying a specific instance of some value, pass the location of what you would like to modify.
• If a function takes an address (pointer) as a parameter, it can go to that address if it needs the actual value.
Double Pointers
Arrays in Memory
Arrays of Pointers
Pointer Arithmetic
const
struct
ternary
Live Session Slides




























