指针在C中,一个示例作品,一个不是

发布于 2025-02-01 04:27:04 字数 354 浏览 1 评论 0原文

我有这个代码:

#include <stdio.h>


int main(void) {
    char greeting1[10] = "Hello!"; //works
    char *greeting2 = "Hello!";    //works
    int numbers1[10]= {1,2,3};     //works
    int *numbers2 = {1,2,3};       //doesn't work

}

对我来说,使用指针适用于“ engering2”是没有意义的,而对于“ numbers2”而言。有没有一种简单的方法来解释为什么这不适用于“ numbers2”?

I have this code:

#include <stdio.h>


int main(void) {
    char greeting1[10] = "Hello!"; //works
    char *greeting2 = "Hello!";    //works
    int numbers1[10]= {1,2,3};     //works
    int *numbers2 = {1,2,3};       //doesn't work

}

It doesn't make sense to me that using pointers work for "greeting2", but not for "numbers2". Is there a simple way to explain why this does not work for "numbers2"?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

心碎的声音 2025-02-08 04:27:04

在表达式中使用的阵列将其转换为指针转换为其第一元素。

在此声明中,

char *greeting2 = "Hello!";

字符串文字具有数组类型char [7],并将其隐式转换为指向其第一个元素。此指针表达式用于初始化指针engreing2

当字符串字面用来初始化数组时,则使用其元素(作为初始化器)来初始化数组的元素。

char greeting1[10] = "Hello!";

实际上,上述声明等同于

char greeting1[10] = { 'H', 'e', 'l', 'l', 'o', '!', '\0' };

本声明中,

int *numbers2 = {1,2,3};

您正在尝试使用包含多个初始化器的支撑列表初始化标量对象。这样的初始化无效。要初始化标量对象,您可以在括号中仅使用一个初始化器。

您可以使用复合文字来初始化指针,例如

int *numbers2 = ( int[] ){1,2,3};

在这种情况下,具有数组类型int [3]再次被隐式转换为指向其第一个元素的指针,此地址用于初始化该指针指针数字2

Arrays used in expressions with rare exceptions are converted to pointers to their first elements.

In this declaration

char *greeting2 = "Hello!";

the string literal has the array type char[7] and is implicitly converted to a pointer to its first element. This pointer expression is used to initialize the pointer greeting2.

When a string literal is used to initialize an array then its elements are used (as initializers) to initialize elements of the array.

char greeting1[10] = "Hello!";

In fact the above declaration is equivalent to

char greeting1[10] = { 'H', 'e', 'l', 'l', 'o', '!', '\0' };

In this declaration

int *numbers2 = {1,2,3};

you are trying to initialize a scalar object with a braced list that contains more than one initializer. Such an initialization is invalid. To initialize a scalar object you may use only one initializer in braces.

You could initialize the pointer with a compound literal like

int *numbers2 = ( int[] ){1,2,3};

In this case the compound literal having the array type int[3] again is implicitly converted to a pointer to its first element and this address is used to initialize the pointer numbers2.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文