Skip to content
Snippets Groups Projects
Commit 9c1c233e authored by Mactavish's avatar Mactavish
Browse files

updates on strings and arrays

parent d480dbfb
Branches
Tags
No related merge requests found
...@@ -288,8 +288,41 @@ These are common in many codebases, and the first time you see them, you might b ...@@ -288,8 +288,41 @@ These are common in many codebases, and the first time you see them, you might b
## Arrays ## Arrays
Array variable is simply a **pointer** to the **0th** element. So `char *string` and `char string[]` are _nearly_ identical declarations. But the subtle difference is that, `char *string` is viewed as a string literal and can not be modified via subscript. In contrast, `char string[]` is just a character array whose elements can be modified via subscript.
So we have `a[i] == *(a + i)`. But unfortunately, when an array is passed to the function, it is passed as a pointer, and the size information is **lost**.
Arrays in C are very primitive:
- An Array in C does not have the information to its own length, not like `arr.length` in other languages
- Array's bounds are not checked at all
- So we can easily access off the end of an array
- We muss pass the array and its size together to any function that is going to manipulate it
## Strings ## Strings
String in C is just an array of characters: `char string[] = "hello world"`.
String in C is **null-terminated** which means the special character `\0` marks the end of a string.
There are lots of auxiliary functions provided by the standard library in `<string.h>`, but be aware of how they treat the null character.
For example, the `strlen` function returns the length of the string **excluding** the null character.
There are lots of ways to initialize a string:
```c
char c[] = "abcd";
char c[50] = "abcd";
char c[] = {'a', 'b', 'c', 'd', '\0'};
char c[5] = {'a', 'b', 'c', 'd', '\0'};
char str* = "string literal"; // can not be modified via array subscript
```
## C Memory Management ## C Memory Management
## C Compilation Process ## C Compilation Process
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment