473,320 Members | 1,879 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

two dimensional array

im trying to declare a two dimensional array using pointers. but it is not
working, any ideas?
Jul 23 '05 #1
20 2664
* Someonekicked:
im trying to declare a two dimensional array using pointers. but it is not
working, any ideas?


Use std::vector.

For concrete examples, see chapter 1.7 of
<url: http://home.no.net/dubjai/win32cpptut/html/w32cpptut_01.html>.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 23 '05 #2
"Someonekicked" writes:
im trying to declare a two dimensional array using pointers. but it is not
working, any ideas?


Like this:

#include <iostream>
using namespace std;

//------------------
void test2(int b[][5])
{
cout << b[2][3] << endl;
}
//====================
int main()
{
int(*a)[5] = new int[3][5];
a[2][3] = 2048;
test2(a);
cin.get();
}
Jul 23 '05 #3
Val

"Someonekicked" <so***********@comcast.net> wrote in message news:Vs********************@comcast.com...
| im trying to declare a two dimensional array using pointers. but it is not
| working, any ideas?
|

Programming is communicating in the first place.
1) Does the matrix know the rows and columns at compile time or run time only?
2) Why isn't working? Where is the code?
3) How did you express the Matrix? As a single array of row*col size, or as an array holding arrays?

See the C++ faq lite (google it) for your first hints.
Jul 23 '05 #4

Someonekicked wrote:
im trying to declare a two dimensional array using pointers. but it is not working, any ideas?


There are many ways to create a two dimensional array in C++.

You can use a vector of vectors
std::vector<std::vector<int> > My2dOfInt;

You can also use a custom class, or you can use a pointers of pointers.

Check out the following link for examples, and for different methods.
http://www.tek-tips.com/faqs.cfm?fid=5575

Jul 23 '05 #5
I would say, the simplest way would be

int **p ;
p = new int *[ROWS] ;
for( int i = 0 ; i < ROWS ; i++ )
p[i] = new int[COLUMNS];

But everyone seems to suggest vectors...

Jul 23 '05 #6

Angad wrote:
I would say, the simplest way would be

int **p ;
p = new int *[ROWS] ;
for( int i = 0 ; i < ROWS ; i++ )
p[i] = new int[COLUMNS];

But everyone seems to suggest vectors...

You're missing the code to free the above allocated data.
Using **p (pointer of pointers) you need code for allocating the data,
code for keeping track of the sizes of the rows and columns and code to
deallocated the data.

So using **p is not the simplest approach.
It's far easier to use a vector that wraps all the logic behind a safe
container.
Your above code can be done in one line of code by using vectors.
vector<vector<int> > My2DArr(ROWS, std::vector<int>(COLUMNS));

IMHO, this one line of code is far simpler then the pointer of pointer
code, and the required tracking code, plus the required deallocation
code needed for the pointer of pointer method.

Jul 23 '05 #7
Val
| Your above code can be done in one line of code by using vectors.
| vector<vector<int> > My2DArr(ROWS, std::vector<int>(COLUMNS));

std::valarray for numbers.

Or single array acting as a Matrix:
int* Matrix = new int[ROWS*COLS];

But I think it's a nice excercise to do it the ** way :)
Jul 23 '05 #8
Someonekicked wrote:
I'm trying to declare a two dimensional array using pointers.


Take a look at the FAQ

http://www.parashift.com/c++-faq-lite/

[16.16] How do I allocate multidimensional arrays using new?
Jul 23 '05 #9
Yes, I agree that vectors simplify the matter a lot by reducing our
coding, but I must say that they add to a lot of unnecessary code to
the executable code. Compile time increases manyfold (I'm talking from
a personal experience). I'd say, use vectors only when basic data types
cannot be used....

As for the freeing of the memory, the code is:

for( int i = 0 ; i < ROWS ; i++ )
delete [] p[i] ;
delete [] p ;

This code will definitely be faster than using vectors... (please
comment if I'm wrong)

Jul 23 '05 #10
Val
|
| This code will definitely be faster than using vectors... (please
| comment if I'm wrong)

You can't know in this stage. But the word "definetely" is a strong expression...
And once again, std::valarray is made for numbers. Very efficient. One needs to test thoroughly if a std::valarray implementation
needs to be replaced by an own version.
Much more can be said, but these are the big lines.
Jul 23 '05 #11
Man, talk about conicidence. I was about to post a thread relating to
this topic.

I am interested in 2-D arrays. However, I'd like to do this task
without calling the vector class.

I would like to use pointers to declare a multidimensional array
without using the vector class. I can declare arrays and do addition,
transposition, and inversion. But what I'd like to know is how to
**MULTIPLY** two multidimensional arrays using C++ just using Dev
C++/GCC.

Jul 23 '05 #12
Val

"Bushido Hacks" <bu**********@gmail.com> wrote in message news:11**********************@f14g2000cwb.googlegr oups.com...
| Man, talk about conicidence. I was about to post a thread relating to
| this topic.
|
| I am interested in 2-D arrays. However, I'd like to do this task
| without calling the vector class.
|
| I would like to use pointers to declare a multidimensional array
| without using the vector class. I can declare arrays and do addition,
| transposition, and inversion. But what I'd like to know is how to
| **MULTIPLY** two multidimensional arrays using C++ just using Dev
| C++/GCC.
First implement the 2d array. See the C++ faq on a nice hint.
When you succeeded, multiplication is going to be straightforward.
Jul 23 '05 #13
Val
|
| First implement the 2d array. See the C++ faq on a nice hint.
| When you succeeded, multiplication is going to be straightforward.

But right now you really should consider std::valarray :).
Unless it is your homework and you're not allowed to.
Jul 23 '05 #14

Angad wrote:
Yes, I agree that vectors simplify the matter a lot by reducing our
coding, but I must say that they add to a lot of unnecessary code to
the executable code. Compile time increases manyfold (I'm talking from a personal experience). I'd say, use vectors only when basic data types cannot be used....

As for the freeing of the memory, the code is:

for( int i = 0 ; i < ROWS ; i++ )
delete [] p[i] ;
delete [] p ;

This code will definitely be faster than using vectors... (please
comment if I'm wrong)


More then likely there's not that much of a measurable difference
between the vector destructor, and the above code.
Even if there was, I would still prefer to use the vector which IMHO,
is a cleaner, and safer method.
Also, in general, a vector is more efficient at iterations then using a
pointer of pointers.

Jul 23 '05 #15
You're right, I tried out std:valarray - I can't compare to pointers,
but definitely faster than usual vectors...


And Val, don't mind me saying this, but looks like you're hell-bent on
convincing everyone about std:valarray... is it because it's got your
name in it ;)

Jul 23 '05 #16
Val

"Angad" <ka*********@gmail.com> wrote in message news:11**********************@o13g2000cwo.googlegr oups.com...
| You're right, I tried out std:valarray - I can't compare to pointers,
| but definitely faster than usual vectors...
|
|
|
|
| And Val, don't mind me saying this, but looks like you're hell-bent on
| convincing everyone about std:valarray... is it because it's got your
| name in it ;)

Good one :)

AS a matter of fact, right now I am in the very process of implementing many versions of matrices for testing purposes.
Jul 23 '05 #17
Hi
I'll say one thing here. Given the following situations
1. The data type of the elements is primitive/basic
2. One-time memory allocation and deallocation is required in any
object
I think the BEST way is to manually allocate and deallocate memory by
new and delete. I'm sure vector implements lots of bound checks, and
that increases allocation code itself, forget about manipulations. I'm
an undergrad, and I've started using vectors wherever necessary, only
because it reduces my coding drastically, so that I can concentrate on
the algorithm of the problem given to me.
Please comment

ps: to Val: I didn't endorse std:valarray because I haven't used it
much. Does it involve lesser coding than vectors or more?

Jul 23 '05 #18
Angad wrote:

Hi
I'll say one thing here. Given the following situations
1. The data type of the elements is primitive/basic
2. One-time memory allocation and deallocation is required in any
object
I think the BEST way is to manually allocate and deallocate memory by
new and delete. I'm sure vector implements lots of bound checks, and
that increases allocation code itself, forget about manipulations.


Usually all of that is NOT true.
The difference in using 'vector' versus 'homemade manually allocated
arrays' is that the former works out of the box while the later
gives lots of troubles. In terms of runtime both versions usually
are next to each other, sometimes std::vector is faster, sometimes
the homegrown version is faster. But they are usually that close
to each other that it really doesn't matter what you use, that is:
if execution speed is your only concern.

--
Karl Heinz Buchegger
kb******@gascad.at
Jul 23 '05 #19
Bushido Hacks wrote:
It's not that I'm not allowed to use the vector class, I'm just not
interested in using vectors. I'm more comfortable with Arrays and
Pointers

I like Angad's method.

Here is what I'd really like to do with his codes:

class Matrix{
public:
Matrix(int rows = 4, int cols = 4){
setDims(rows,cols);
int **p ;
p = new int *[getRows()] ;
for( int i = 0 ; i < getRows() ; i++ ){
p[i] = new int[getCols()];
};
};
Matrix &setDims(int rows,int cols){setRows(rows);setCols(cols);};
Matrix &setRows(int rows){this->rows = rows; return *this;};
Matrix &setCols(int cols){this->cols = cols; return *this;};
int getRows() const {return rows;};
int getCols() const {return cols;};
Matrix printMatrix() const {
for(int i = 0; i < getRows(); i++){
for(int j = 0; j < getCols(); j++){
cout << this[i][j] << " "; // I know this is incorrect, but I'm
just using it
// to illustrate the concept. Please correct if I am wrong.
};
cout << endl;
};
};
Matrix &setIdentity(){
for(int i = 0; i < getRows(); i++){
for(int j = 0; j < getCols(); j++){
this[i][j] = (i == j);
};
};
}; // Identity matrix
~Matrix(){
for( int i = 0 ; i < getRows() ; i++ ){
delete [] p[i] ;
};
delete [] p ;
};
private:
int rows, cols;
};

// such that I can do this

int main(){
Matrix m(4,4); // yes I know I already declared defaults
// but I'm just using this as an example
m.setIdentity().printMatrix();
return 0;
};

The desired output should be

1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1


Just an idea, instead of printMatrix() you could make your matrix directly
with cout as in:

cout << m << endl;

I use this function in my Matrix2D...I think I got if from the C++-Lite FAQ:

(m and n represent the dimension of the Matrix2D as in: m x n)

friend ostream& Matrix2D::operator<<(ostream &out, const Matrix2D &matrix2d)
{
for(int i = 0; i < matrix2d.m; i++)
{
for(int j = 0; j < matrix2d.n; j++)
out << matrix2d.matrix[i][j] << " ";
out << endl;
}

return out;
}

--
Alvin
Jul 23 '05 #20
Angad wrote:
Yes, I agree that vectors simplify the matter a lot by reducing our
coding, but I must say that they add to a lot of unnecessary code to
the executable code.
What unnecessary code do they add, for example?
Compile time increases manyfold (I'm talking from a personal
experience).
Enable pre-compiled headers in your compiler.
I'd say, use vectors only when basic data types cannot be used....
I'd say that tracking down even one memory allocation bug in your
code would take longer than adding up all the extra compile time
caused by using vectors.
As for the freeing of the memory, the code is:

for( int i = 0 ; i < ROWS ; i++ )
delete [] p[i] ;
delete [] p ;

This code will definitely be faster than using vectors...


What makes you think that?
It seems likely to me that the vector code will boil down to
exactly that series of deletes. You could examine the
assembly generated by your compiler, and see what the difference
is.

Jul 23 '05 #21

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: ip4ram | last post by:
I used to work with C and have a set of libraries which allocate multi-dimensional arrays(2 and 3) with single malloc call. data_type **myarray =...
6
by: Ruben | last post by:
I'm trying to pass an array of string to a function without knowing how many strings I have beforehand. I've defined one functions as char * insert(char table,int cols, char values); out of...
16
by: rguti | last post by:
Hi, How do I create a two dimensional array? I have created a one dimensional doing this: Dim laFields As ArrayList = New ArrayList How about to do a 2 dimensional?
60
by: Peter Olcott | last post by:
I need to know how to get the solution mentioned below to work. The solution is from gbayles Jan 29 2001, 12:50 pm, link is provided below: >...
5
by: Diffident | last post by:
Hello All, I have a 2-dimensional array that I am storing as a session variable. I have no idea on how I can cast the session variable back to 2-dimensional array. Any pointers? Reference...
22
by: spam.noam | last post by:
Hello, I discovered that I needed a small change to the Python grammar. I would like to hear what you think about it. In two lines: Currently, the expression "x" is a syntax error. I suggest...
6
by: fniles | last post by:
I need to store information in a 2 dimensional array. I understand ArrayList only works for a single dimensional array, is that correct ? So, I use the 2 dimensional array like in VB6. I pass the...
8
by: per9000 | last post by:
Hi all, I have a two-dimensional array of data, f.x int's. We can imagine that the array is "really large". Now I want the data in it and store this in a one-dimensional array. The obvious...
272
by: Peter Olcott | last post by:
http://groups.google.com/group/comp.lang.c++/msg/a9092f0f6c9bf13a I think that the operator() member function does not work correctly, does anyone else know how to make a template for making two...
5
by: nelly0 | last post by:
developing a program that will manipulate noise levels (measured in decibels) that is collected by car manufacturers. These noise levels are produced at seven different speeds by a maximum of six...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.