473,769 Members | 7,646 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Passing 2D Dynamic Arrays to Functions?

I have two matrices allocated dynamically in both directions: matrix x and
matrix v.

I want to pass these matrices into a function by reference. What I have
written down isn't working... can somebody enlighten me on how I would
solve this?

Here is what my prototype and my function look like:

=============== =============== =============== ========

double distance(int k, int i, int& n, double *x[], double *v[]);
double distance(int k, int i, const int& n, double *x[], double *v[])
{
double w;
for (int j=0; j<n; j++)
{
w = w + pow((x[k][j] - v[i][j]), 2);
}
return w;
}

In addition, I have another question. Is it possible to call this function
by only using the first two parameters (i and k)?
"x" and "v" are the matrices that are being read in and they will always
be used. "n" is a set constant at the beginning of the program that isn't
changed. It would clean up the code if I could just say "distance(i , k)"
and the other three variables would automatically be used.

As it sits now, this is how the function would be called (given that I
could get that double pointer issue sorted out... LOL!)

double q = 0;
for (int i=0; i<C; i++)
{
for (int k=0; k<Nm; k++)
{
q = q + pow((u[i][k]),m)*distance(k , i, n, x, v);
}
}

Any help would be greatly appreciated. :)

Jul 22 '05 #1
6 2197

"fivelitermusta ng" <fi************ **@shaw.ca> wrote in message
news:a6******** *************** *******@localho st.talkaboutpro gramming.com...
I have two matrices allocated dynamically in both directions: matrix x and
matrix v.

I want to pass these matrices into a function by reference. What I have
written down isn't working... can somebody enlighten me on how I would
solve this?

Here is what my prototype and my function look like:

=============== =============== =============== ========

double distance(int k, int i, int& n, double *x[], double *v[]);
double distance(int k, int i, const int& n, double *x[], double *v[])
{
double w;
for (int j=0; j<n; j++)
{
w = w + pow((x[k][j] - v[i][j]), 2);
}
return w;
}
Ho hum. What does 'doesn't work' mean? Does it give a compile error, a run
time error, does it run to completion but not give the results you expect?
What are the results you expect?

Is this really the code you have? The obvious problem is that w is an
uninitialised variable.

How exactly are you allocating your arrays, and how exactly are you calling
the function? Both of these are potential issues.

Why did you choose 'double *x[]', instead of 'double **x', any particular
reason?

So many questions.

In addition, I have another question. Is it possible to call this function
by only using the first two parameters (i and k)?
Yes, if you write a class. Put x and v and n as members of the class and
distance as a method of the class. Since you're programming C++, and C++ is
all about classes, this might be a good oppotunity to get some practise with
them.
"x" and "v" are the matrices that are being read in and they will always
be used. "n" is a set constant at the beginning of the program that isn't
changed. It would clean up the code if I could just say "distance(i , k)"
and the other three variables would automatically be used.


john
Jul 22 '05 #2

Yuk! Your approach doesn't use any of the featurs of C++, you
are still thinking in C!

My suggestion would be to use the STL to generate your matrices. You
can have a general Matrix class, with the matrix represented internally as
variable of type vector of vectors.
I've seen this published somewhere, I can't remember where, but you can
probably
find it. As a taste, look at the code below. You can encapsulate things
quiet nicely
and include the various matrix operations, multiply, addition, negation
etc, as
overloaed operators, perhaps even provide meaning to / using the inverse
operation.
Throw exceptions if the matrices are incompatible or operation is undefined.

( take a look at Scott Myer's book Effective C++, I think he handles two
dimensional
subscripting very nicely using a proxy class, my approach below is a bit
hacked. )

#include <vector>
using namespace std;

class Matrix
{
public:
// create zero matrix
Matrix( int M, int N )
{
for (int m=0; m<M ; m++)
{
vector<double> row;

for (int n=0; n<N; n++)
{
row.push_back(0 .0);
}
_matrix.push_ba ck(row);
}
}

Matrix( const Matrix& m )
{
// copy constructor
}

public:
vector<double>& operator[]( int rowindex)
{
return _matrix[rowindex];
}

public:
Matrix operator*( const Matrix& m )
{
// check validity of multiplying these matrices
// throw execption / bomb out if necessary.
}
private:
vector< vector<double> > _matrix;
};
// test program to illustrate the [][] indexing of the matrix elements
int main(int argc, char* argv[])
{
Matrix m(3, 3 );
printf (" M[0][0]=%f\n", m[0][0]);
m[0][0]=1.0;
printf (" M[0][0]=%f\n", m[0][0]);
double foo = m[0][0];
printf (" M[0][0]=%f\n", m[0][0]);
return 0;
}

"fivelitermusta ng" <fi************ **@shaw.ca> wrote in message
news:a6******** *************** *******@localho st.talkaboutpro gramming.com...
I have two matrices allocated dynamically in both directions: matrix x and
matrix v.

I want to pass these matrices into a function by reference. What I have
written down isn't working... can somebody enlighten me on how I would
solve this?

Here is what my prototype and my function look like:

=============== =============== =============== ========

double distance(int k, int i, int& n, double *x[], double *v[]);
double distance(int k, int i, const int& n, double *x[], double *v[])
{
double w;
for (int j=0; j<n; j++)
{
w = w + pow((x[k][j] - v[i][j]), 2);
}
return w;
}

In addition, I have another question. Is it possible to call this function
by only using the first two parameters (i and k)?
"x" and "v" are the matrices that are being read in and they will always
be used. "n" is a set constant at the beginning of the program that isn't
changed. It would clean up the code if I could just say "distance(i , k)"
and the other three variables would automatically be used.

As it sits now, this is how the function would be called (given that I
could get that double pointer issue sorted out... LOL!)

double q = 0;
for (int i=0; i<C; i++)
{
for (int k=0; k<Nm; k++)
{
q = q + pow((u[i][k]),m)*distance(k , i, n, x, v);
}
}

Any help would be greatly appreciated. :)

Jul 22 '05 #3
>>Ho hum. What does 'doesn't work' mean? Does it give a >>compile error, a
run
time error, does it run to completion but not give the >>results you expect?What are the results you expect?

Is this really the code you have? The obvious problem is >>that w is an
uninitialis ed variable.

How exactly are you allocating your arrays, and how exactly >>are you
calling
the function? Both of these are potential issues.

Why did you choose 'double *x[]', instead of 'double **x', >>any particularreason? So many questions.


Well, I chose to use double *x[] because it seemed intuitive to me. How
would I go about initializing it using **x? And how would I pass a matrix
initialized like that by reference?

The entire program is written however it is all monolithic and it does
work properly. I just want to put some of these operations into functions
for clarity and easier coding.

The error that it gives me is a compile time error.
"Error : function call 'distance(int, int, const int, double **, double
**)' does not match
'std::distance< ...>(T0, T0)'
'distance(int, int, int &, double **, double **)'
clustering.cpp line 157 q = q + pow((u[i][k]),m)*distance(k , i, n, x,
v);"

Jul 22 '05 #4

"fivelitermusta ng" <fi************ **@shaw.ca> wrote in message
news:ca******** *************** *******@localho st.talkaboutpro gramming.com...
Ho hum. What does 'doesn't work' mean? Does it give a >>compile error, a runtime error, does it run to completion but not give the >>results you expect?What are the results you expect?

Is this really the code you have? The obvious problem is >>that w is an
uninitialis ed variable.

How exactly are you allocating your arrays, and how exactly >>are you
calling
the function? Both of these are potential issues.

Why did you choose 'double *x[]', instead of 'double **x', >>any particularreason?So many questions.


Well, I chose to use double *x[] because it seemed intuitive to me. How
would I go about initializing it using **x? And how would I pass a matrix
initialized like that by reference?

The entire program is written however it is all monolithic and it does
work properly. I just want to put some of these operations into functions
for clarity and easier coding.

The error that it gives me is a compile time error.
"Error : function call 'distance(int, int, const int, double **, double
**)' does not match
'std::distance< ...>(T0, T0)'
'distance(int, int, int &, double **, double **)'
clustering.cpp line 157 q = q + pow((u[i][k]),m)*distance(k , i, n, x,
v);"


OK well I can now see the other problem

Look at your prototype

double distance(int k, int i, int& n, double *x[], double *v[]);

and your function

double distance(int k, int i, const int& n, double *x[], double *v[])

There's an extra const in the function which isn't in the prototype.

Personally I would change both to plain int, there's not much point in const
int&, and you don't need int&.

And fix that uninitialised variable w.

john
Jul 22 '05 #5
Essentially I had "n" defined at the beginning of the program as a
constant. When I was calling the function it wasn't expecting "n" to be a
constant. I just changed both the definitions to contain const and that
did the trick...

Thanks a lot for the help.

Jul 22 '05 #6

"fivelitermusta ng" <fi************ **@shaw.ca> wrote in message
news:ed******** *************** *******@localho st.talkaboutpro gramming.com...
Essentially I had "n" defined at the beginning of the program as a
constant. When I was calling the function it wasn't expecting "n" to be a
constant. I just changed both the definitions to contain const and that
did the trick...

Thanks a lot for the help.


Glad you worked it out. The essential point is that the prototype and the
actual function should have the same signature.

Just because n is a constant is no reason to use const int&, as I said a
plain int is better.

john
Jul 22 '05 #7

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

Similar topics

4
1583
by: Vannela | last post by:
How can i achieve the dynamic arrays concept in C#? I have used the ArrayLists of C# but in few cases it is failing like when i pass these dynamic arrays a arguments to functions b'coz in those functions directly i cant assign the arraylist values to other variables (as they are objects) How can i do that? In unmanaged code it is like this which i want to do it in
58
10179
by: jr | last post by:
Sorry for this very dumb question, but I've clearly got a long way to go! Can someone please help me pass an array into a function. Here's a starting point. void TheMainFunc() { // Body of code... TCHAR myArray; DoStuff(myArray);
4
7697
by: Scott Lyons | last post by:
Hey all, Can someone help me figure out how to pass a dynamic array into a function? Its been giving me some trouble, and my textbook of course doesnt cover the issue. Its probably something simple, but its just not popping into my mind at the moment. My little snippet of code is below. Basically, the studentID array is dynamic so it will fit any length of a Student's Name. What I'm trying to do is place this chunk of code into a...
9
4804
by: justanotherguy63 | last post by:
Hi, I am designing an application where to preserve the hierachy and for code substitability, I need to pass an array of derived class object in place of an array of base class object. Since I am using vector class(STL), the compiler does not allow me to do this. I do realize there is a pitfall in this approach(size of arrays not matching etc), but I wonder how to get around this problem. I have a class hierachy with abstract base...
2
1971
by: dave.harper | last post by:
I'm relatively new to C++, but have a question regarding functions and arrays. I'm passing a relatively large array to a function several thousand times during the course of a loop, and it seems to get bogged down. Do the arrays previously passed to the function stay memory resident? If not, what's causing it and what can I do to correct it? Thanks, Dave
2
3325
by: NM | last post by:
Hello all, I am supposed to do some mixed programming with c++ and fortran. I was succeeful in exchanging the 2D arrays from fortran to c++ and the other way, but was unable to that same with the 3D arrays, the values passed are not all the same. I am also pasting the fortran and c++ codes so that you could have a look at them. ////C++ Code
6
2981
by: Materialised | last post by:
Hi Everyone, I apologise if this is covered in the FAQ, I did look, but nothing actually stood out to me as being relative to my subject. I want to create a 2 dimensional array, a 'array of strings'. I already know that no individual string will be longer than 50 characters. I just don't know before run time how many elements of the array will be needed. I have heard it is possible to dynamically allocate memory for a 2
10
3171
by: Pete | last post by:
Can someone please help, I'm trying to pass an array to a function, do some operation on that array, then return it for further use. The errors I am getting for the following code are, differences in levels of indirection, so I feel it must have something to do with the way I am representing the array in the call and the return. Below I have commented the problem parts. Thanks in advance for any help offered. Pete
60
10193
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: > http://groups.google.com/group/comp.lang.c++/msg/db577c43260a5310?hl > >Another way is to create a one dimensional array and handle the >indexing yourself (index = row * row_size + col). This is readily >implemented in template classes that can create dynamically allocated >multi-dimensional...
0
9589
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9423
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10048
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9996
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9865
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8872
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6674
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5304
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3963
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.