你的代码块是正确的.有了这个声明:
char **output_str = malloc(sizeof(char*));
output_str是一个指向char指针的char指针,或者它可以看作是char的二维数组或char的矩阵.
图形表示:
Memory Address | Stored Memory Address Value
----------------------------------------------
0 | .....
1 | .....
2 | .....
3 | .....
4 | .....
5 | .....
6 | .....
. | .....
. | .....
. | .....
n-1 | .....
想象一下,内存是一个非常大的数组,你可以通过它的内存地址访问位置(在这种情况下,我们已经将地址简化为自然数.实际上它们是十六进制值). “n”是存储器的总量(或大小).由于存储器计数并从0开始,因此大小相当于n-1.
1.当你调用时:
char **output_str = malloc(sizeof(char*));
操作系统和C编译器为我们做了,但我们可以认为我们的内存已被更改.例如.内存地址3现在有一个指向名为output_str的char指针的char指针. .
Memory Address | Name - Stored Memory Address Value (it points to ...)
-----------------------------------------------------
0 | .....
1 | .....
2 | .....
3 | output_str = undefined
4 | .....
5 | .....
6 | .....
. | .....
. | .....
. | .....
n-1 | .....
2.如果我们说:
*output_str = malloc(sizeof(char));
内存已再次更改.例如.内存地址0现在有一个名为* output_str的字符指针.
Memory Address | Name - Stored Memory Address Value (it points to ...)
-----------------------------------------------------
0 | *output_str = undefined
1 | .....
2 | .....
3 | output_str = 0
4 | .....
5 | .....
6 | .....
. | .....
. | .....
. | .....
n-1 | .....
3.我们声明一个静态实例化的char:
char a = 'a';
所以我们的内存再次改变了,它放在了MemoryAddress [6] =’a’:
Memory Address | Name -> Stored Memory Address Value (it points to ...)
------------------------------------------------------
0 | *output_str = undefined
1 | .....
2 | .....
3 | output_str = 0
4 | .....
5 | .....
6 | a = 'a' // 'a'is static memory
. | .....
. | .....
. | .....
n-1 | .....
Lastly, we invoke *output_str = &a; we are now telling char pointer *output_str to point to/reference the previously instantiated char a.
所以我们的最终记忆将如下所示:
Memory Address | Name - Stored Memory Address Value (it points to ...)
-----------------------------------------------------
0 | *output_str = 6
1 | .....
2 | .....
3 | output_str = 0
4 | .....
5 | .....
6 | a = 'a' // 'a'is static memory
. | .....
n-1 | .....
更多的信息
06005