简体   繁体   English

在 C 中声明一个带有指针的数组

[英]Declare an array with pointer in C

Why is this syntax illegal in C?为什么这个语法在 C 中是非法的?

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

Aren't arrays and pointers the same thing? arrays 和指针不是一回事吗? Why would this work and not the above?为什么这行得通而不是上面的?

int a[] = {1,2,3};
int *b = a;

Why is this syntax illegal in C?为什么这个语法在 C 中是非法的?

In int a[] = {1,2,3};int a[] = {1,2,3}; , the {1,2,3} is a syntax for providing initial values of the things being initialized. , {1,2,3}是一种语法,用于提供被初始化事物的初始值。 A list of values in braces is a general notation for listing initial values.大括号中的值列表是列出初始值的通用符号。 It is not a notation for representing an array.它不是表示数组的符号。

The declaration says a is an array, but that is just in its int a[] part.声明说a是一个数组,但这只是在它的int a[]部分。 The {1,2,3} does not indicate an array—it just provides a list of values, and it could be used for non-array objects, such as providing values for the members of a structure. {1,2,3}并不表示数组——它只是提供一个值列表,它可以用于非数组对象,例如为结构的成员提供值。

In int *a = {1,2,3};int *a = {1,2,3}; , the int *a part defines a to be a pointer. int *a部分将a定义为指针。 A pointer just has one value in it—the address of something (or null).一个指针只有一个值——某物的地址(或空值)。 So it does not make sense to initialize it with multiple values.所以用多个值初始化它是没有意义的。 To initialize a pointer, you need to provide an address for it to point to.要初始化指针,您需要为其提供指向的地址。

There is a notation in C for representing an array of given values. C 中有一个表示给定值数组的符号。 It is called a compound literal, and can be used for types in general, not just arrays.它被称为复合文字,一般可用于类型,而不仅仅是 arrays。 Its syntax is “( type ) { initial values }”.它的语法是“(类型){初始值}”。 So we can create an array with (int []) {1, 2, 3} .所以我们可以用(int []) {1, 2, 3}创建一个数组。 A pointer could be defined and initialized to point to this array with int *a = (int []) {1, 2, 3};可以使用int *a = (int []) {1, 2, 3}; . . However, this should be done with care.但是,这应该小心。 Such an array is temporary (has automatic storage duration that ends when execution of its associated block ends) when defined inside a function, so the pointer will become invalid when the function returns (or before, if it is in an inner block).当在 function 中定义时,此类数组是临时的(具有在其关联块执行结束时结束的自动存储持续时间),因此当 function 返回时(或之前,如果它在内部块中),指针将变为无效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM