Passing array by reference

N

news.tiscali.dk

This might be a really simple question, but here goes: How can I pass an
array to a function and have the function put values into that array? Some
code to clearify (mat is a matrix class)

float m[16];
mat = matX * matZ * matT;
mat.getElements( m );
Render.setMeshTransform( m );

In my matrix class I have

void getElements( TYPE tMatrix[] ) {
tMatrix = m_tElements;
}

float m_tElements[16];

This, of course, works one way; getElements can access the values in
tMatrix. But when the function returns, m is not filled with the values from
m_tElements. So, is it possible to somehow pass an array by reference,
(without new'ing it!)?
 
R

Ron Natalie

news.tiscali.dk said:
This might be a really simple question, but here goes: How can I pass an
array to a function and have the function put values into that array? Some
code to clearify (mat is a matrix class)


Arrays are always passed by reference (this is a goofy inconsistency that's
been in C since the dawn of time). Well, what really happens is that the thing
that looks like an array declaration in your getElements function really gets
converted to a TYPE* tMatrix. So you're passing a pointer to the first float
in the array. This isn't your problem.

The real problem you are running into, is that arrays are also inconsistant
in that they can't be assigned.
void getElements( TYPE tMatrix[] ) {
tMatrix = m_tElements;
}

You'll have to copy the elements individually:
for(int i = 0; i < 16; ++i) tMatrix = m_tElements;
for example.

However, what's really easier is to use vector. vector is an array like
object that behaves normally (unlike arrays). If you want to pass it by
reference, you can use the C++ reference syntax.

#include <vector>
using std::vector;

vector<float> m(16);
mat.GetElements(m);

vector<float> m_tElements(16);
void getElements(vector<TYPE>& tmatrix) {
tmatrix = m_tElements;
}
 
J

John Almer

However, what's really easier is to use vector. vector is an array like
object that behaves normally (unlike arrays). If you want to pass it by
reference, you can use the C++ reference syntax.

#include <vector>
using std::vector;

vector<float> m(16);
mat.GetElements(m);

vector<float> m_tElements(16);
void getElements(vector<TYPE>& tmatrix) {
tmatrix = m_tElements;
}

Op should also check out "vector::swap()" which many programmers don't seem
to be aware of (not referring to you personally :). It's much faster than
direct assignment where applicable.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,142
Messages
2,570,820
Members
47,367
Latest member
mahdiharooniir

Latest Threads

Top