C++中int*和int[]的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4851234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:46:55  来源:igfitidea点击:

Difference between int* and int[] in C++

c++

提问by EFreak

Context: C++ Consider the example below

上下文:C++ 考虑下面的例子

class TestClass
{
private:
    int A[];
    int *B;

public:
    TestClass();
};

TestClass::TestClass()
{
    A = 0; // Fails due to error: incompatible types in assignment of `int' to `int[0u]'
    B = 0; // Passes
}

A = 0 fails but B = 0 succeeds. What's the catch? What exactly is A? A constant pointer? How do I initialize it then?

A = 0 失败但 B = 0 成功。有什么问题?A究竟是什么?一个常量指针?那我该如何初始化呢?

采纳答案by Nawaz

The only difference between them is that int A[]in a classwould not compile, and should not compile!

它们之间唯一的区别是int A[]在一个类中不会编译,并且不应该编译!

Comeau C++ compiler gives this error:

Comeau C++ 编译器给出了这个错误:

"ComeauTest.c", line 4: error:   
incomplete type is not allowed   
      int A[];
          ^ 
"ComeauTest.c", line 4: error:   
incomplete type is not allowed   
      int A[];
          ^ 

Wikipediasays,

维基百科说,

Comeau C/C++ has been regarded as the most standards-conformant C++ compiler.

Comeau C/C++ 一直被认为是最符合标准的 C++ 编译器。

I therefore would suggest : Don't write such code even if your compiler compiles it.

因此,我建议:即使您的编译器编译了它,也不要编写这样的代码。

回答by David Rodríguez - dribeas

The question "what is the difference between int* and int[]?" is a less trivial question than most people will think of: it depends on where it is used.

问题“int* 和 int[] 之间有什么区别?” 这是一个比大多数人想象的更重要的问题:这取决于它的使用位置。

In a declaration, like extern int a[];it means that somewhere there is an array called a, for which the size is unknown here. In a definition with aggregate initialization, like int a[] = { 1, 2, 3 };it means an array of a size I, as programmer, don't want to calculate and you, compiler, have to interpret from the initialization. In a definition without initialization, it is an error, as you cannot define an array of an unknown size. In a function declaration (and/or) definition, it is exactly equivalent to int*, the language specifies that when processing the types of the arguments for functions, arrays are converted into pointers to the contained type.

在声明中,就像extern int a[];它意味着某处有一个名为 的数组a,其大小在这里未知。在具有聚合初始化的定义中,就像int a[] = { 1, 2, 3 };它意味着一个大小为 I 的数组,作为程序员,我不想计算,而您,编译器,必须从初始化中进行解释。在没有初始化的定义中,这是一个错误,因为你不能定义一个未知大小的数组。在函数声明(和/或)定义中,它完全等同于int*,该语言指定在处理函数的参数类型时,将数组转换为指向所包含类型的指针。

In your particular case, as declaration of members of a class, int a[];is an error, as you are declaring a member of an incomplete type. If you add a size there, as in int a[10]then it becomes the declaration of an array of type intand size 10, and that will reserve space for 10 intinside each object of the class. While on the other hand, int *bwill only reserve space for a pointer to integers in the class.

在您的特定情况下,作为类成员的声明,int a[];是错误的,因为您声明的是不完整类型的成员。如果在那里添加一个大小,int a[10]那么它将成为类型int和大小为 10的数组的声明,这将为int类的每个对象内保留 10 个空间。而另一方面,int *b只会为类中的整数指针保留空间。

回答by Jose Villalta

A[] is an array with its size undefined. You need to declare it like this:

A[] 是一个大小未定义的数组。您需要像这样声明它:

int A[SIZE];

int A[大小];

then initialize it like this:

然后像这样初始化它:

A[0] = 0, A[1] = 5,

A[0] = 0, A[1] = 5,

etc

等等

回答by Asha

Ais an array, and in C++ you need to specify the array size when you define the variable itself i.e. you need to do something like int A[10]. Then you can access individual elements using A[0], A[1]etc. Bis a pointer, so doing B=0;sets the pointer to NULL. If you don't want to specify the size at compile time, but still want array like syntax you can use std::vector<int>.

A是一个数组,在 C++ 中,您需要在定义变量本身时指定数组大小,即您需要执行类似int A[10]. 然后您可以使用A[0], A[1]etc.访问单个元素B是一个指针,因此B=0;将指针设置为 NULL。如果您不想在编译时指定大小,但仍需要类似数组的语法,您可以使用std::vector<int>.

回答by Daniel Mo?mondor

int A[]is an memory range inside the class instance, where int *Bis a pointer that you may or may not initialize later.

int A[]是类实例内的内存范围,其中int *B是您稍后可能会或可能不会初始化的指针。

so

所以

A=0means that you want to change a pointer that cannot be changed,

A=0意味着你想改变一个不能改变的指针,

where

在哪里

B=0means that you are changing a pointer to point to 0x00000000

B=0意味着您正在更改指针以指向 0x00000000

回答by Shinnok

The code snapshot you have there should not compile since A[]is effectively a zero sized array, thus an incomplete type, which is not allowed in class specifications. For e.g. Visual Studio fails to compile this with these errors:

你在那里的代码快照不应该编译,因为A[]它实际上是一个零大小的数组,因此是一个不完整的类型,这在类规范中是不允许的。例如,Visual Studio 无法编译这些错误:

1>...\test.h(4) : warning C4200: nonstandard extension used : zero-sized array in struct/union 1>
Cannot generate copy-ctor or copy-assignment operator when UDT contains a zero-sized array 1>...\test.h(5) : error C2229: class 'TestClass' has an illegal zero-sized array

1>...\test.h(4):警告 C4200:使用非标准扩展:结构/联合
中的零大小数组 1> 当 UDT 包含零大小数组时,无法生成复制构造函数或复制赋值运算符 1> ...\test.h(5):错误 C2229:类“TestClass”有一个非法的零大小数组

To initialize and use A[]you must declare it as static and initialize it with file scope like this:

要初始化和使用,A[]您必须将其声明为静态并使用文件范围初始化它,如下所示:

class TestClass
{
private:
    static int A[];
    int *B;

public:
    TestClass();
};

TestClass::TestClass()
{
    //A = 0;  Yes this is wrong, see below.
    B = 0; // Passes
}

int TestClass::A[] = {1,2,3};

As for A = 0 this is wrong too and Visual Studio will complain with this error, which is self explanatory:

至于 A = 0 这也是错误的,Visual Studio 会抱怨这个错误,这是不言自明的:

1>..\test.h(13) : error C2440: '=' : cannot convert from 'int' to 'int []' 1> There are no conversions to array types, although there are conversions to references or pointers to arrays.

1>..\test.h(13) : error C2440: '=' : cannot convert from 'int' to 'int []' 1> 没有到数组类型的转换,尽管有到引用或指向的指针的转换数组。

LE: Also see David Rodríguez - dribeasanswer for a complete interpretation of zero sized arrays.

LE:另请参阅David Rodríguez - dribeas对零大小数组的完整解释的答案。

回答by Bort

long answer short, A is of type array and B is of type pointer to int.

长答案简而言之,A 是数组类型,B 是指向 int 的指针类型。

A[] initializes an array of zero size, which you cannot assign a value to.

A[] 初始化一个大小为零的数组,您不能为其赋值。

Btw, you can ask C++ yourself with:

顺便说一句,你可以问 C++ 自己:

#include <iostream>
#include <typeinfo>

using namespace std;

class TestClass{
  private:
    int A[];
    int* B;
  public:
    TestClass();
};

TestClass::TestClass(){
  cout<<"Type A: "<<typeid(A).name()<<endl;
  cout<<"Type B: "<<typeid(B).name()<<endl;
}

int main(int argc, char** argv){
  TestClass A;

  return 0;
}