Lecture 3: C Pointers, Arrays, Strings¶
True and False¶
- False
- 0 (integer, all bits are 0)
NULL(pointer)
- True
- Anything else
Tips
Now, True and False are provided in stdbool.h
Memory is a single huge array¶
Consider memory to be a 'byte-addressed' array
- Each cell of this array has an address associated with it
- Each cell also stores some value
Pointers store addresses
Pointer: A variable that contains the address of another variable

Pointers Syntax

Warning
In this scenario, when we change *p, actually we are change the value in "What p points to"
So if we print x, we can find it into 5 correspondingly
Pointers are useful when passing parameters¶
Passing by value¶
C passes parameters by value
- A function parameter gets assigned a copy of the argument value.

Passing in pointer¶
Review: when we change
*p, actually we are change the value in "What p points to"
So we can get a function to change a value, pass in a pointer.

Common Bug: Garbage Addresses¶
The situation is that: Declaring a pointer just allocates space to hold the pointer, but it does not initialize the pointer to point to anything.
- It does not allocate something to be pointed to !!!

What is NULL pointer¶
The "NULL" pointer, all bits are 0.
Note
It's a very easy definition :)

If we define char* p = NULL, what contained in p is 0x00000000
Pointers and Struct¶

We can review this process:
| C | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | |
Pointer Arithmetic¶
a[i] = *(a+i)pointer + n== addn*sizeof("whatever pointer is pointing to")to memory addresspointer - n== subtractn*sizeof("whatever pointer is pointing to")to memory address

How to use a function to change a pointer¶
eg. Suppose we want increment_ptr to change where q points to.
错误示范:increment_ptr(q)

正确示范:increment_ptr(&q)
原理: 我们设计一个“指向q指针”的指针

Arrays¶
char *stringandchar string[]are nearly identical declarations- When we use
arr (array name), we actually mean the start_address ofarrarray

Attentions


Strings¶

string is actually a char array, and its final bit is always set to \0
Warning
Don't mistake string with include<string> in C++
We don't have string type in C