gpt4 book ai didi

c - 复合/字符串文字存储在内存中的什么位置?

转载 作者:太空狗 更新时间:2023-10-29 16:59:42 26 4
gpt4 key购买 nike

我读过;

A compound literal is a C99 feature that can be used to create an array with no name. Consider the example:

int *p = (int []){3, 0, 3, 4, 1};

p points to the first element of a five- element array containing 3, 0, 3, 4, and 1.

其实我想知道,这个数组没有名字,会不会存入内存?
换句话说,如果是

char* str = "hello"

字符串"hello"将存储在内存中的什么位置?

最佳答案

使用指针运算。所以

p[0], p[1], ...

*p, *(p + 1), ...

事情是这样的。在 C 语言中,您可以为 intchar 等基本类型提供很好的文字,甚至可以使用字符串文字。所以,我们可以很容易地说出这样的话

int length(char *s);
int len = length("Hello, World!");

在C99中,加入了复合字面量的概念来处理“数组字面量”和“结构字面量”。因此,我们现在可以这样说:

int sum(int a[], int n);
int total = sum((int []){ 17, 42 }, 2);

这是使用复合文字来表示“数组文字”。

Actually I want to know, Is this array will stored in memory or not as it doesn't have a name?

是的,在内存中。

我认为您的困惑源于此。 p 有一个名字。 (int []){3, 0, 3, 4, 1} 没有。恰好 p 的值是 (int []){3, 0, 3, 4, 1} 的地址。当然 (int []){3, 0, 3, 4, 1} 在内存中;它将位于您的可执行文件的数据段中。您只是没有任何名称来引用它。

关于c - 复合/字符串文字存储在内存中的什么位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17890301/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com