你的代码块是正确的。使用以下声明:
char **output_str = malloc(sizeof(char*));
output_str是一个指向字符指针的指针,或者它可以被看成是一个字符二维数组,或者是一个字符矩阵。
图形化表示:
Memory Address | Stored Memory Address Value
----------------------------------------------
0 | .....
1 | .....
2 | .....
3 | .....
4 | .....
5 | .....
6 | .....
. | .....
. | .....
. | .....
n-1 | .....
假想一下
内存(memory)像是一个非常大的数组,你可以通过它的内存地址访问位置。在这种情况下,我们简化地址为自然数。实际上它们是十六进制值。"n"是内存的总大小(或容量)。由于内存从0开始计数,因此大小等同于 n-1。
1. 当你调用:
char **output_str = malloc(sizeof(char*));
操作系统和C编译器会代替我们完成这个过程,但我们可以认为内存已经被改变了。例如,内存地址3现在具有指向指向字符指针的字符指针,名为 output_str
。
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现在有一个char指针,名为*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 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 | .....
最后,我们调用
*output_str = &a;
,现在我们告诉字符指针
*output_str
指向/引用以前实例化的
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 | .....
更多信息
Now printf("Value: " + a) will output "Value: a"
printf("Value: " + *output_str[0]) will also output "Value: a"
And printf("Value: " + **output_str) will output "Value: a"
malloc
返回的是void *
类型,可以隐式转换为任何其他指针类型。你的陈述意味着malloc
分配的空间可以用作存储char *
值的空间。 - M.M