Contents

Lec4-C intro:Pointers, Arrays, Strings

C intro: Pointers, Arrays, Strings

1
int (*fn) (void *, void *) = &foo; // pointer to function

arrow operator -> is used to access members of a struct pointed to by a pointer.

NULL pointer is used to indicate an invalid pointer.

1
2
3
if (p == NULL) {
    // handle error
}

谈到了地址对齐 -> word alignment

/lec4-c-intropointers-arrays-strings/image.png

1
2
3
sizeof(arg)

sizeof(structtype)

经典问题之数组名是指针

/lec4-c-intropointers-arrays-strings/image-1.png

1
2
3
4
5
char *foo() {
    char arr[10];
    return arr; 
    // A BIG mistake! 函数栈回收时,arr指针指向的空间可能被释放掉了,导致程序崩溃
}

always end with a null character \0 😉

Segmentation fault :s

或许rust可能更安全

1
2
3
4
5
6
7
8
void incrementPtr(int *p) {
    p += 1;
    // wrong again! have to ...
}

void incrementPtr(int **p) {
    (*p) += 1; // correct
}

注意引用传递即可