char *array 和 char array[] 之间的内存差异是什么?

Ant*_*nko 5 c memory arrays pointers

当我执行下一个代码时

int main()
{
    char tmp[] = "hello";
    printf("%lp, %lp\n", tmp, &tmp);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我得到了相同的地址。但对于下一个代码,它们会有所不同

int main()
{
    char *tmp = "hello";
    printf("%lp, %lp\n", tmp, &tmp);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

您能解释一下这些示例之间的内存差异吗?

Dav*_*ica 5

char tmp[] = "hello";是一个 6 个字符的数组,初始化为"hello\0"(它具有自动存储持续时间并驻留在程序堆栈中)。

char *tmp = "hello";是一个指针,char使用驻留在只读内存中的字符串文字的地址进行初始化"hello\0"(通常在.rodata可执行文件的部分内,除了少数实现之外的所有实现都是只读的)。

如上所述,当您char tmp[] = "hello";访问时,数组将转换为指向 的第一个元素的指针tmp。它有类型char *tmp当您获取(例如)的地址时,&tmp它将解析为相同的地址,但具有完全不同的类型。它将是一个指向 array-of 的指针 char[6]。正式类型是char (*)[6]. 由于类型控制指针算术,因此当您推进指针时,使用不同类型进行迭代将产生不同的偏移量。前进tmp就会前进到下一个char。前进的地址tmp将前进到下一个 6 字符数组的开头。

当你有了时,char *tmp = "hello";你就有了一个指向char. 当您获取地址时,结果是pointer-to-pointer-to char。形式类型char **反映了间接的两个层次。前进tmp前进到下一个chartmp前进到下一个指针的地址。