Tama Yoshi
Tama Yoshi

Reputation: 313

Are ** and * [] the same?

I have this pair of declaration/definition on my Eclipse IDE (in a .h and .hpp respectively):

 A( T* [] );

and

 A<T>::A(T ** p_proc) { ... }

The first is an array of pointers, the other a pointer of pointers. I am confused in that they are interchangeable here; Eclipse complains if I replace the ** by * [], throwing a syntax error. Eclipse does not raise errors when I do the opposite, though.

My question is twofold; are these two notations fundamentally the same? Are T [][] and T ** the same as well? Why does Eclipse throw a syntax error when the hpp file has a type of * [], but not in the header?

Upvotes: 1

Views: 125

Answers (3)

oblitum
oblitum

Reputation: 12008

If your Eclipse is not understanding the following case, it's a bug:

template<typename T>
struct A{
    A(T **p_proc);
};

template<typename T>
A<T>::A(T *p_proc[]) {}

It's perfectly fine.

Check question about arrays decaying to pointers to understand it in more detail.

Upvotes: 1

Brian Bi
Brian Bi

Reputation: 119069

My question is twofold; are these two notations fundamentally the same?

No, they are not. T*[] has type array of unknown size of pointer to T whereas T** has type pointer to pointer to T. Arrays and pointers are not identical in general.

However, declaring a function parameter to be of array type is exactly the same as declaring it to be of the corresponding pointer type. If a function parameter is specified to have array type then it's "adjusted" to have the corresponding pointer type. In the same way, int* and int[] aren't the same type, but when you write a function that takes an int[] parameter, it's adjusted so that it takes an int* parameter. (Note that this adjustment is suppressed if the parameter is a reference to array.)

Are T [][] and T ** the same as well?

Actually T[][] is not a valid type at all. In a multidimensional array type, only the first bound may be omitted.

Why does Eclipse throw a syntax error when the hpp file has a type of * [], but not in the header?

Probably because you're writing T*[] p_proc. The correct declarator is T* p_proc[].

Upvotes: 6

Jerry Coffin
Jerry Coffin

Reputation: 490058

They're the same for parameters to functions. A function parameter can't have the type "array of T". If you try to declare a function parameter as having a type "array of T", the compiler will (silently) adjust it to "pointer to T".

That's not the case elsewhere though. Just for example, having something like:

//filea.cpp
int x[SIZE];

and:

//fileb.cpp
extern int *x;

...will not work.

Upvotes: 3

Related Questions