大概是写这么多年 C(++) 以来第一次正式学 C (虽然其实在康奈尔学过一遍C++)
Compiling C Program
| 1 | # compile hello.c and name the executable as default (a.out) | 
We usually write return 0, this exit code 0 means
EXIT_SUCCESS.
| Prototype | Definition | 
|---|---|
| prototype - declare a function (write down its name) | definition - define a function (write down its content) | 
| .hstand for “header” and it contains prototype of
function | .cstand for “code” and it contains definition of
function | 
Complex & Custom Data Types
struct
| 1 | struct rect_t { | 
### typedef
The keyword typedef allows a programmer to create a new
type.
| 1 | struct _rect_t { ... }; | 
Now we can create instance of the new type: (Note how this is different from a struct instance declaration)
| 1 | rect_t myRect; | 
Strings
- char *strstr(const char *haystack, const char *needle): finds the first occurrence of the substring needle in the string haystack.
- sprintf(char *str, const char *format, ...): “prints out” formatted output to a string str, but instead of really printing them out,- sprintfbuffers the output to the string.(- sprintf(str, "Pi = %f", 3.14);will set- strto be- Pi = 3.14)
Dynamic Memory Allocation
Consider the following program:
| 1 | int * initArray(int howLarge) { | 
We cannot do this because the space allocated to myArray
is only inside the scope of initArray and will be freed
once we exit this function. So what we want is dynamic memory
allocation so the memory will be allocated at a dynamic heap
instead of the call stack.
| 1 | int *p = malloc(6 * sizeof(int)); // memory allocation | 
We can then rewrite the above function as:
| 1 | int * initArray(int howLarge) { | 
Note the following when you use free:
| 1 | // you cannot free something on the stack | 
Debugging C in VSCode
- Install the extension “GDB Debugger - Beyond” 
- Replace what’s in - launch.json - configurationswith the following codes:- 1 
 2
 3
 4
 5
 6
 7
 8
 9- "configurations": [ 
 {
 "type": "by-gdb",
 "request": "launch",
 "name": "Launch(gdb)",
 "program": "${fileDirname}/${fileBasenameNoExtension}",
 "cwd": "${workspaceRoot}"
 }
 ]