Question:
c++ dynamic array question?
Anon
2011-11-28 09:24:49 UTC
say i have

int* name = new int[rows][colls];

why doesnt this work? im wanting to create a 2d dynamic array :\
Four answers:
?
2011-11-28 19:06:11 UTC
new[] returns a pointer to the first element of the array. In this case, you're creating a 1D array of 1D arrays, so it returns a pointer to the first 1D array (that is, to the first row). The following compiles (assuming colls is a compile-time constant)



     int (*name)[colls] = new int[rows][colls];



demo: https://ideone.com/jGy8e



If your second dimension is not known at compile time, you cannot construct a 2D array type.



Your options, from best to worst:



An actual matrix from a matrix library (e.g. from boost)

Self-written Matrix class using 1D underlying storage (vector or valarray)

Vector of vectors

1D array of pointers to individually-allocated 1D arrays (as suggested by another answer)
?
2016-10-16 16:31:56 UTC
@jbaksta: no longer asserting you're incorrect, yet i might have an interest to be sure the benchmarking code and compiler innovations and environment you was sure that vectors are slower than close by dynamic arrays.
Kyle
2011-11-28 10:00:18 UTC
You're trying to do a multidimensional array with only a single pointer.



try

int **name = new int[];

name = new int* [rows];

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

name[i] = new int[colls];

}
2011-11-28 09:46:15 UTC
hi you are visite the link and read the book now..





http://kldp.org/files/c+in+21+days.pdf


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Continue reading on narkive:
Loading...