Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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's the catch? What exactly is A? A constant pointer? How do I initialize it then?

like image 661
EFreak Avatar asked Jan 31 '11 13:01

EFreak


People also ask

What is the difference between int * and int []?

It's just what you prefer to use, both are integer type arrays. There is no difference in functionality between both styles of declaration. Both declare array of int.

What is a int * in C?

The int type in C is a signed integer, which means it can represent both negative and positive numbers. This is in contrast to an unsigned integer (which can be used by declaring a variable unsigned int), which can only represent positive numbers.

What is * a [] in C?

char *A[] is an array, and char **A is a pointer. In C, array and pointer are often interchangeable, but there are some differences: 1. with "char *A[]", you can't assign any value to A, but A[x] only; with "char **A", you can assign value to A, and A[x] as well.

What is the difference between int array [] and int [] array?

They are semantically identical. The int array[] syntax was only added to help C programmers get used to java. int[] array is much preferable, and less confusing. The [] is part of the TYPE, not of the NAME.


1 Answers

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.

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.

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 int and size 10, and that will reserve space for 10 int inside each object of the class. While on the other hand, int *b will only reserve space for a pointer to integers in the class.

like image 192
David Rodríguez - dribeas Avatar answered Sep 22 '22 18:09

David Rodríguez - dribeas