Stackoverflow-Com

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

OverflowAI is here! AI power for your Stack Overflow for Teams knowledge community.

Learn
Products Search… Log in Sign up
more

Home Declaring a pointer to Ask Question

Questions
multidimensional array and
Tags
allocating the array
Asked 13 years, 7 months ago Modified 4 years, 1 month ago Viewed 94k times
Users

Companies
I've tried looking but I haven't found anything with a definitive
answer. I know my problem can't be that hard. Maybe it's just that
LABS 28 I'm tired..

Jobs NEW Basically, I want to declare a pointer to a 2 dimensional array. I want


to do it this way because eventually I will have to resize the array. I
Discussions
have done the following successfully with a 1D array:

COLLECTIVES
int* array;
Communities for your favorite array = new int[somelength];
technologies. Explore all
Collectives

I would like to do the following with a 2D array but it won't compile:


TEAMS

int* array;
array = new int[someheight][somewidth];
Ask questions, find answers
and collaborate at work with
Stack Overflow for Teams. The compiler gives me an error stating that ‘somewidth’ cannot
appear in a constant-expression. I've tried all sorts of combinations
Explore Teams
of ** and [][] but none of them seem to work. I know this isn't that
Create a free Team complicated...Any help is appreciated.

c++ pointers multidimensional-array

Share Improve this question Follow edited Oct 4, 2014 at 11:20


M.M
By clicking “Accept all cookies”, you agree Stack Exchange 140k 23 212 373
can store cookies on your device and disclose information in
accordance with our Cookie Policy. asked Oct 11, 2010 at 7:22
vince88
Accept all cookies Necessary cookies only 3,289 5 27 28

Add a comment
Customize settings
Report this ad

6 Answers Sorted by: Highest score (default)

const int someheight = 3;


const int somewidth = 5;
51 int (*array)[somewidth] = new int[someheight][somewidth];

Share Improve this answer Follow edited Apr 4, 2020 at 17:21


luca
7,398 7 42 57

answered Oct 11, 2010 at 7:34


Tony The Lion
62.5k 68 248 422

12 Unlike the other answers here, this one actually answers the question,
which was how to declare a pointer to a multidimensional array - not a
jagged array. This is an important differentiation for performance-
sensitive applications. It works if "somewidth" is a constant, and only the
"someheight" changes. If you look at how this 2D array is laid out in
memory - it's all together and contiguous, with no more than the single
"new" memory allocation done. The answer by Alexander Rafferty is also
good if the width is also dynamic. The other answers are slow because
they do a ton of mallocs... – James Johnston Jan 14, 2014 at 16:03

1 How do you properly destroy this array? delete[] array; I assume so since
it's really a contiguous piece of memory. – Dicer Mar 1, 2019 at 21:53

Just to clarify James Johnston's important note. Arrays and pointers are
not the same: an array can decay into a pointer, but a pointer doesn't
carry state about the size/configuration of the data to which it points.
This prevents using pointers of pointers as a contiguous memory. Still
the decay of an N dimensional array to a pointer to N-1 dimensional
array is allowed by c++ since you can lose the leftmost dimension and
still being able to correctly access array elements with N-1 dimension
information. Details in stackoverflow.com/a/3925968/1201614 – luca Apr
4, 2020 at 17:37
Add a comment

I just found this ancient answer still gets read, which is a shame
since it's wrong. Look at the answer below with all the votes instead.
17
Read up on pointer syntax, you need an array of arrays. Which is the
same thing as a pointer to a pointer.

int width = 5;
int height = 5;
int** arr = new int*[width];
for(int i = 0; i < width; ++i)
arr[i] = new int[height];

Share Improve this answer Follow edited May 23, 2017 at 12:25
Community Bot
1 1

answered Oct 11, 2010 at 7:29


dutt
8,039 12 53 86

2 Did you try this? It doesn't compile (if height and width are both
variables) – The Archetypal Paul Oct 11, 2010 at 7:32

Yes I have tried this and still get the same error with the compiler. it will
say that "‘width’ cannot appear in a constant-expression" – vince88 Oct
11, 2010 at 7:32

1 If I were to access an element of this array would it just be arr[width]


[height]? – vince88 Oct 11, 2010 at 7:47

It is very well specified that when declaring a 2D-Array the row argument
can be a variable , but the column argument has to be constant only.
– krishna Nov 26, 2014 at 4:37

3 No, array of array and array of pointers are not the same thing. Why is
this post accepted ? The answer of Tony The Lion is the correct one, this
one is completely wrong. – Bregalad Mar 23, 2015 at 15:10

Add a comment

A ready to use example from here, after few seconds of googling


with phrase "two dimensional dynamic array":
8
int **dynamicArray = 0;

// memory allocated for elements of rows.


dynamicArray = new int *[ROWS];
// memory allocated for elements of each column.
for( int i = 0 ; i < ROWS ; i++ ) {
dynamicArray[i] = new int[COLUMNS];
}

// free the allocated memory


for( int i = 0 ; i < ROWS ; i++ ) {
delete [] dynamicArray[i];
}
delete [] dynamicArray;

Share Improve this answer Follow answered Oct 11, 2010 at 7:32
Arun
20.1k 10 52 60

2 This is an array of arrays, not really a 2D one. – Alexander Rafferty Oct 11,
2010 at 7:38

3 @Alexander Rafferty: I see -- what is the difference between "array of


arrays" and "2D arrays'? – Arun Oct 11, 2010 at 7:45

6 @ArunSaha, this is old, but to answer your question and for anyone else
that stumbles across this, a 2-D array is contiguous in memory; a
dynamic array of dynamic arrays is contiguous in the first dimension, but
each array in the second dimension is stored separately – Stephen Lin
Mar 14, 2013 at 3:08

@Stephen Lin: Appreciate your explanation! Say there is a also int


staticArray[ ROWS ][ COLUMNS ]; . Also assume that there is a
function printArray( int arr[ ROWS ][ COLUMNS ] ) which
access and prints all the elements as arr[ i ][ j ] . One could pass
either staticArray or dynamicArray to that function and it would
work, correct? There is structural difference and your point is valid.
However, since there is no behavioral difference, I tend to consider the
difference as a implementation detail. – Arun Mar 14, 2013 at 22:49

@ArunSaha, no that's the point, you can pass int[N] (array of N


integers) as int * (pointer to integer) but you can't pass int[R][C]
(array of R of array of C integers) as an int ** (pointer to pointer to
integer); there is no implicit conversion and if you cast it to make it work
you'll corrupt memory; int [R][C] decays to int (*)[C] (pointer
to array of C integers) instead...see this answer – Stephen Lin Mar 14,
2013 at 22:54

Show 3 more comments

I suggest using a far simpler method than an array of arrays:

8 #define WIDTH 3
#define HEIGHT 4

int* array = new int[WIDTH*HEIGHT];


int x=1, y=2, cell;
cell = array[x+WIDTH*y];
I think this is a better approach than an array of an array, as there is
far less allocation. You could even write a helper macro:

#define INDEX(x,y) ((x)+(WIDTH*(y)))

int cell = array[INDEX(2,3)];

Share Improve this answer Follow answered Oct 11, 2010 at 7:41
Alexander Rafferty
6,193 4 34 57

Add a comment

Personally, my preference is to use a syntactic trick to declare a


pointer to the dynamically sized multi-dimensional array. This works
3 in compilers that support Variable Length Arrays (VLAs), which all
C++ compilers should, and most current C compilers.

The basic idea is captured in this:

void bar (int *p, int nz, int ny, int nx) {
int (*A)[ny][nx] = (int(*)[ny][nx]) p;

"p" points at the (contiguous) block of space you want to treat as a


multi-dimensional array. "A" has the same value as "p", but the
declaration makes the compiler treat references to "A" in the multi-
dimensional way you want. For example:

#include <iostream>
using namespace std;

void bar (int *p, int nz, int ny, int nx)
{
int (*A)[ny][nx] = (int(*)[ny][nx]) p;

for (int ii = 0; ii < nz; ii++) {


for (int jj = 0; jj < ny; jj++) {
for(int kk = 0; kk < nx; kk++) {
A[ii][jj][kk] = ii*1000000 + jj*1000 + kk;
}
}
}
}

void out (int *p, int nz, int ny, int nx)
{
int (*A)[ny][nx] = (int(*)[ny][nx]) p;
cout << A[11][22][33] << endl;
}
int main (void)
{
int NX = 97;
int NY = 92;
int NZ = 20;
int *space = new int [NZ * NY * NX];

bar (space, NZ, NY, NX);


out (space, NZ, NY, NX);
return 0;
}

Running this produces the output "11022033"

The declaration of the "A" alias is a little weird looking, but it allows
you to directly and simply use the desired multi-dimensional array
syntax

Share Improve this answer Follow answered Sep 1, 2016 at 18:06


Bron Nelson
31 1

Add a comment

I think this will do

1 int r, c ;
std::cin>>r>>c ;
int *array = new int[r*c] ;

You can input the values by doing something like this

for (int i = 0 ; i < r ; i++){


for (int j = 0 ; j < c ; j++){
std::cin>>array[i *c + j] ;
}
}

Share Improve this answer Follow answered Oct 4, 2014 at 11:04


Tasdik Rahman
2,250 1 27 37

Add a comment

Your Answer
Sign up or log in
Sign up using Google

Sign up using Facebook

Sign up using Email and Password

Post as a guest
Name

Email
Required, but never shown

Post Your By clicking “Post Your Answer”, you agree to our terms of service and
Answer acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged
c++ pointers multidimensional-array or ask your own question.

The Overflow Blog

Why do only a small percentage of GenAI projects actually make it into...

Spreading the gospel of Python

Featured on Meta

Our Partnership with OpenAI

What deliverables would you like to see out of a working group?

The [price] tag is being burninated


Policy: Generative AI (e.g., ChatGPT) is banned

Linked

2 C++ How to declare pointer to 2D array

13 3D array C++ using int [] operator

5 In C/C++, is char* arrayName[][] a pointer to a pointer to a pointer OR a pointer to


a pointer?

0 Why 2D arrays using pointers gives false values?

0 What is this representation of a pointer to an array?

0 Declaring multidimensional floating or unsigned dynamic array in C++

0 Passing parameters to a functions

Related

0 How to declare an array of pointers to multidimensional arrays

0 declaring a 2D array of pointer objects

0 pointers to a multidimensional array in classes

3 Using pointers in array

0 pointers to multidimensional arrays in class

3 Multi-dimensional arrays and pointers in C++

3 Allocating memory to pointer multidimensional array with new

1 Storing data into a multidimensional array

0 Pointer to multidimensional array C++

0 Multi dimensional array and pointer in c++

Hot Network Questions


Can there be more than one global maximums of a function?

Order of numerical solver when calculating difference between forwards and backwards
solution

Show don't tell with a blind character

What is this Nintendo 64 DD flyswatter game from?

Does a time varying electric field always generate a Magnetic field?


Does Popper's falsifiability criterion hold any utility?

What is the purpose of the top tube on bicycles?

I lost the keys for a gate's lock. Where can I find a replacement cylinder or how can I get
new keys?

Quantum fields can leak out of the light cone?

Would it count as a story if nothing bad happens to the character anywhere in the story?

Use l3seq sequence in command requiring \ExplSyntaxOff

Proverb for someone who mistakenly assumes he has found the right answer and is
unwilling to accept his error?

Decode Caesar cipher based on a given text

Does target of Geas know the penalty for disobeying?

Print macro in \addplot node label

Source to learn nowadays halacha

Negation of "I think therefore I am"?

How to provide opportunities for role playing in a single player campaign focused on
travelling and wilderness survival?

How do I speedup this simulation program

Is this considered cheating?

I cleaned the grease off an old floppy drive’s motor; do I need to lubricate it?

Why are the Lion Air and Ethiopian Airlines crashes being litigated in the US?

In the US, does the Social Security benefit calculator assumes you work until the retire
age?

Is this "School of the Wyrm" wizard subclass I found balanced?

Question feed

STACK OVERFLOW
Questions Help

PRODUCTS
Teams Advertising Collectives Talent

COMPANY
About Press Work Here Legal Privacy Policy Terms of Service Contact Us Cookie Settings Cookie Policy

STACK EXCHANGE NETWORK


Technology Culture & recreation Life & arts Science Professional Business API Data
Blog Facebook Twitter LinkedIn Instagram

Site design / logo © 2024 Stack Exchange Inc; user contributions licensed under CC BY-SA. rev 2024.5.15.9214

You might also like