473,803 Members | 3,410 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

pointers and dynamic arrays

I'm having some trouble with poitners and dynamic arrays (a matrix).
Given this function I have a few questions.

void func(int* mat, int rows, int columns, char* out)
{
...
}

My first question is in main, how is a matrix defined that can be sent
to this function?

I can do it like:

int** matrix;
matrix = new int*[numRows];
for(int i=0; i< numRows; i++)
matrix[i] = new int[numColumns];

and by sending func(matrix,num Rows, numColumns, out). But the only
way I can get it to accept this is by changing the first argument to
accept int** instead of int*. It has to accept int* so I'm not quite
sure how to declare a matrix in main.

My next question is how can I set an element of the matrix to a
location of the char* array?

I can easily use cout<<mat[3][3]; in the func and it'll output that
certain element on to the screen, but I can't get it to go to an
element in the character array.

I know this would be a lot easier to do this with out pointers and
just using arrays and not poitners to arrays so don't tell me that...

Thanks

Apr 21 '07 #1
3 2462
re***********@g mail.com wrote:
I'm having some trouble with poitners and dynamic arrays (a matrix).
Given this function I have a few questions.

void func(int* mat, int rows, int columns, char* out)
{
...
}

My first question is in main, how is a matrix defined that can be sent
to this function?
That would probably be expecting mat as a contiguous array of rows...

i.e. element (i,j) is probably

mat[ i* columns + j ] or mat[ i + j * rows ]

The best way to do this is with a matrix class of which there are plenty
of examples on this NG.
>
I can do it like:

int** matrix;
matrix = new int*[numRows];
for(int i=0; i< numRows; i++)
matrix[i] = new int[numColumns];
That's not unusual but probably not what is needed here.
>
and by sending func(matrix,num Rows, numColumns, out). But the only
way I can get it to accept this is by changing the first argument to
accept int** instead of int*. It has to accept int* so I'm not quite
sure how to declare a matrix in main.

My next question is how can I set an element of the matrix to a
location of the char* array?

I can easily use cout<<mat[3][3]; in the func and it'll output that
certain element on to the screen, but I can't get it to go to an
element in the character array.

cin >mat[3][3]; // maybe ?
>
I know this would be a lot easier to do this with out pointers and
just using arrays and not poitners to arrays so don't tell me that...

Thanks
Apr 21 '07 #2
On Apr 21, 1:50 am, "repairman2...@ gmail.com"
<repairman2...@ gmail.comwrote:
I'm having some trouble with poitners and dynamic arrays (a matrix).

Given this function I have a few questions.

void func(int* mat, int rows, int columns, char* out)
{
...

}

My first question is in main, how is a matrix defined that can be sent
to this function?

I can do it like:

int** matrix;
matrix = new int*[numRows];
for(int i=0; i< numRows; i++)
matrix[i] = new int[numColumns];

and by sending func(matrix,num Rows, numColumns, out). But the only
way I can get it to accept this is by changing the first argument to
accept int** instead of int*. It has to accept int* so I'm not quite
sure how to declare a matrix in main.

My next question is how can I set an element of the matrix to a
location of the char* array?

I can easily use cout<<mat[3][3]; in the func and it'll output that
certain element on to the screen, but I can't get it to go to an
element in the character array.

I know this would be a lot easier to do this with out pointers and
just using arrays and not poitners to arrays so don't tell me that...

Thanks
Write a matrix class, makes its a LOT easier and keeps your data
encapsulated.
You can now pass an instance of a matrix by reference.
You might consider a solution with std::vector instead of primitive
arrays.
This one has a rudimentary copy ctor, op(row, col), and out_of_bounds
checking.
type T could be anything, including a matrix.

The code needs work, probably will expose some bugs under scrutiny,
could also benefit from some std algorithms.

#include <iostream>
#include <ostream>
#include <stdexcept>

template< typename T,
const size_t Row,
const size_t Col >
class Matrix
{
T array[Row][Col];
public:
// ctor
Matrix() : array() { }
Matrix(const Matrix& copy)
{
for(size_t r = 0; r < Row; ++r)
{
for(size_t c = 0; c < Col; ++c)
{
array[r][c] = copy.array[r][c];
}
}
}
// member functions
void set(const size_t row, const size_t col, const T& t)
{
check_bounds(ro w, col);
array[row][col] = t;
}
T get(const size_t row, const size_t col) const
{
check_bounds(ro w, col);
return array[row][col];
}
T operator()(cons t size_t row, const size_t col)
{
return get(row, col);
}
private:
void check_bounds(co nst size_t row, const size_t col) const
{
if( ((0 row) || !(Row row)) || ((0 col) || !(Col col)) )
{
throw std::runtime_er ror("access out of bounds!");
}
}
};

int main()
{
Matrix< int, 10, 10 matrix;
try {

std::cout << "matrix[2][2] = ";
std::cout << matrix.get(2, 2);
std::cout << std::endl;

matrix.set(2, 2, 99);
std::cout << "matrix[2][2] = ";
std::cout << matrix.get(2, 2);
std::cout << std::endl;

Matrix< int, 10, 10 copy_matrix(mat rix);
std::cout << "copy_matri x[2][2] = ";
std::cout << copy_matrix(2, 2); // op( )
std::cout << std::endl;

// errors...
// matrix.get(-1, -1);
// matrix.get(10, 9);
// matrix.get(0, 10);
// matrix.get(10, 10);

Matrix< double, 3, 12 d_matrix;
Matrix< Matrix< int, 4, 4 >, 6, 8 matrix_matrix;
}
catch (const std::exception& r_e) {
std::cout << "\nerror: ";
std::cout << r_e.what() << std::endl;
}
}

/*
matrix[2][2] = 0
matrix[2][2] = 99
copy_matrix[2][2] = 99
*/

___
You can provide default template parameters too.

template< typename T = int,
const size_t Row = 10,
const size_t Col = 10 >
class Matrix_10x10
{
...
};

Apr 21 '07 #3
I know, setting up a matrix class would be easier. That I can do with
no problem, I've set up classes for matrices, vectors, quarternions
and all that fun stuff in the past... They really didn't teach us
much on pointers in school. Everything was STL and data structures,
so all this older c stuff is pretty new to me. I understand the
concept of pointers and how to use them, just never did anything along
these lines. If I can figure out this example then I think everything
could click and I'd be fine.

The only information I had to work with was just what needs to be
passed into the function and what needs to be done with it. The
algorithm I did with ease, just stuck on the format it is supposed to
be in. I made an assumption that the matrix would follow the form of
mat[i][j] where i is the row, and j is the column. I'm not really too
worried with how it's sent, just a curiosity kind of thing.

As for the 2nd question, I guess my intention wasn't as clear as I
thought. I'm just trying to figure out how to append an element of
the matrix to the outbuffer, I came across itoa() a few minutes ago to
convert the element from an int to char but how do I get it to append
each individual element to the outbuffer and I'll need to append a
comma and a space after each one.

Thanks

Apr 21 '07 #4

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

Similar topics

7
2459
by: Squignibbler | last post by:
Hi all, I have a question regarding the C++ programming language regarding the nature of the relationship between pointers and arrays. If the statement MyArray is functionally identical to *(MyArray+x), what statement is functionally identical to MyArray? I ask this question because when I create a dynamic array with one
4
2231
by: Konstantin Shemyak | last post by:
I have a big structure tree. All leaves are scalar values (no pointers). Present are arrays, structures and unions. I want to be able to store/read the content of the structure in/from a file, and in a readable format. This is needed to provide manually constructed test input to a function, which works with this tree. Number of types is huge, and I want to avoid hand-coding read/write functions for each type. Ideally, I'm thinking about...
8
3691
by: Peter B. Steiger | last post by:
The latest project in my ongoing quest to evolve my brain from Pascal to C is a simple word game that involves stringing together random lists of words. In the Pascal version the whole array was static; if the input file contained more than entries, tough. This time I want to do it right - use a dynamic array that increases in size with each word read from the file. A few test programs that make use of **List and realloc( List, blah...
5
1523
by: buda | last post by:
Hi, given the following code, .... int main( void ) { char *a = { "abc", "def", "ghijkl", "o", "prs" }; // for example .... }
5
3764
by: swarsa | last post by:
Hi All, I realize this is not a Palm OS development forum, however, even though my question is about a Palm C program I'm writing, I believe the topics are relevant here. This is because I believe the problem centers around my handling of strings, arrays, pointers and dynamic memory allocation. Here is the problem I'm trying to solve: I want to fill a list box with a list of Project Names from a database (in Palm this is more...
2
2933
by: jccorreu | last post by:
I'm taking in data from multiple files that represents complex numbers for charateristics of different elements. I begin with arrays of doubles and interpolate to get standard values in real and imaginary portions. To this end I have some dynamic arrays of doubles to hold the standardized individual rael and imaginary parts. double *ANreal, *ANimag, *BNreal, *BNimag, *CNreal, *CNimag; ANreal = new double; ANimag = new double;
23
7423
by: sandy | last post by:
I need (okay, I want) to make a dynamic array of my class 'Directory', within my class Directory (Can you already smell disaster?) Each Directory can have subdirectories so I thought to put these in an array. The application compiles but aborts without giving me any useful information. What I suspect is happening is infinite recursion. Each Directory object creates an array of Subdirectories each of which has an array of...
6
1609
by: nembo kid | last post by:
I have these classes: Boss, CommissionWorker, PieceWorker, HourlyWorker all directly derived from Employeer. I create a dynamic object (on heap) for each class:
14
1713
by: stevenruiz | last post by:
Hello All My question mainly is how to use/reference Double Pointers? I am currently trying to understand what the meaning of a 'vector of pointers' means also? What I am trying to do is take a char array and break it up into words omitting the spaces. What needs to be noted is that I am trying to accomplish this only using char ** and char *. Therefore, I am creating it from scratch. Below is code that I have written so far:
0
9700
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
9564
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
10546
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10310
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
7603
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6841
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
5627
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3796
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2970
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.