DevilKing's blog

冷灯看剑,剑上几分功名?炉香无需计苍生,纵一穿烟逝,万丈云埋,孤阳还照古陵

0%

Pointers in C

原文链接

The box named foo_ptr (an int *) is a pointer to a box named foo (an int).

1
int* ptr_a, ptr_b;

1
2
int *ptr_a;
int ptr_b;

相等

The right-left rule for reading C declarations

指针的加减部分

Well, the type of a pointer matters. The type of the pointer here is int. When you add to or subtract from a pointer, the amount by which you do that is multiplied by the size of the type of the pointer. In the case of our three increments, each 1 that you added was multiplied by sizeof(int).

Multiple indirection

1
2
3
4
int    a =  3;
int *b = &a;
int **c = &b;
int ***d = &c;

There is no string type in C.

1
char str[] = "I am the Walrus";

This array is 16 bytes in length: 15 characters for “I am the Walrus”, plus a NUL (byte value 0) terminator. In other words, str[15] (the last element) is 0. This is how the end of the “string” is signaled.

1
2
3
4
5
size_t strlen(const char *str) { Note the pointer syntax here
size_t len = 0U;
while(*(str++)) ++len;
return len;
}

Note the use of pointer arithmetic and dereferencing. That’s because, despite the function’s name, there is no “string” here; there is merely a pointer to at least one character, the last one being 0.