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

Context: C ++ Consider the example below

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 is the catch? What is A? Permanent pointer? How do I initialize it?

+5
source share
7 answers

The only difference between the two is that int A[]the class will not compile and should not compile!

The Comeau C ++ compiler gives this error:

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

Wikipedia says

Como C / C ++ is considered the majority of standards compatible with the C ++ compiler.

Therefore, I suggest: do not write such code, even if the compiler compiles it.

+4
source

: " int * int []?" , : , .

, extern int a[];, , - a, . , int a[] = { 1, 2, 3 };, , I, , , , , . , . (/) int*, , .

, , int a[]; , . , int a[10], int 10, 10 int . , int *b .

+9

A [] - undefined. :

int A [SIZE];

:

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

..

+2

A - , ++ , .. - int A[10]. A[0], A[1] .. B - , B=0; NULL. , , std::vector<int>.

+1

int A[] - , int *B - , .

A=0 , , ,

B=0 , 0x00000000

+1

, , , A[] , , . . Visual Studio :

1 > ...\test.h(4): C4200: : struct/union 1 >
copy-ctor - UDT 1 > ...\test.h(5): C2229: "TestClass"

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};

A = 0, , Visual Studio , :

1 > ..\test.h(13): C2440: '=': 'int' 'int []'   1 > , .

LE: . David Rodríguez - dribeas .

+1

, A B int.

A [] , .

Btw, ++ :

#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;
}
+1

All Articles