1

What is the difference between:

int* a = new int[w]; int** b= new int*[w]; 

and what exactly does this mean: int*[w] and int[w]?

7
  • 1
    Remember that w has to be defined as a const and not as a variable. Commented Jun 15, 2017 at 18:15
  • @RoiHatam: Are you sure? Inside a function, I don't think that's true; a variable size is allowed. G++ (7.1.0) allows it at file scope (int w = 6; int *a = new int[w]; int **b = new int*[w];), even with g++ -O3 -g -std=c++11 -Wall -Wextra -Werror -pedantic …. That's not the same as claiming "the C++ standard allows it", but the -pedantic should trigger a warning (error because of -Werror) if it is in contravention of the standard. Commented Jun 15, 2017 at 18:30
  • We are not a tutoring site. What specifically is unclear? Commented Jun 15, 2017 at 18:40
  • @JonathanLeffler: Wouldn't that be a VLA which are not supported by C++? gcc is a bad reference for standard compliance in default mode, because it has extensions enabled. Commented Jun 15, 2017 at 18:41
  • @Olaf: If the code was: int w = 6; int vla_a[w]; int *vla_b[w]; then you'd be playing with VLAs, and that is not allowed by the C++ standard but G++ does allow it unless you specify -pedantic. As it stands, with the new, you're allocating a dynamic array with a dynamic size — the analogue of int *a = malloc(w * sizeof(int)); in C. Variable sizes are allowed in int *a = new[w];, I'm practically certain. Commented Jun 15, 2017 at 18:44

2 Answers 2

1

In the first case, you're dynamically creating an array of int with w elements. In the second, you create an array of int * with w elements.

The notations int*[w] and int[w] are the types mentioned above: an array of int * of size w, and an array of int of size w respectively.

Sign up to request clarification or add additional context in comments.

3 Comments

int** b= new int*[w]; Are we not creating a 2d matrix in this case with int pointers w?
@Alex: No; you are not creating a 2D matrix. You are creating an array of pointers to int. If you initialize each of those pointers to point to an array of int, then you can treat it more or less as a 2D array — but it still isn't a 2D array (matrix).
@Alex Technically, no. A matrix has a fixed number of rows and columns. The pointers are not initialized, so you need to allocate an array for each one. These sub arrays can be of different sizes. Also, the array of pointers and each array of ints are separate from each other, while a true 2D array is contiguous.
1
int* a = new int[w] 

This first example dynamically allocates w integers.

int** b = new int*[w] 

The second example dynamically allocates w pointers to integers.

1 Comment

And second one simply can be used to implement n-D array, as each element of array is a pointer to an integer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.