So I have this program that deals with one dimensional arrays. I want to expand it to two with array[row][col] how can I do this?
#include %26lt;iostream%26gt;
using namespace std;
int* getArray(int row);
void printArray(int* array, int row);
int main()
{
int row;
cout %26lt;%26lt;"Enter row length: ";
cin%26gt;%26gt;row;
int* array = getArray(row);
cout %26lt;%26lt; "array in main" %26lt;%26lt; endl;
printArray(array, row);
/*int* array2 = getArray();
cout %26lt;%26lt; "array2 in main" %26lt;%26lt; endl;
printArray(array2);
cout %26lt;%26lt; "array in main" %26lt;%26lt; endl;
printArray(array);
delete[] array2;*/
delete[] array;
return 0;
}
int* getArray(int row){
int *array = new int[row];
for ( int i = 0; i %26lt; row; i++ ){
cout %26lt;%26lt; "Enter an integer: ";
cin %26gt;%26gt; array[i];
}
cout %26lt;%26lt; "array in getArray()" %26lt;%26lt; endl;
printArray(array, row);
return array;
}
void printArray(int* array, int row)
{
for ( int i = 0; i %26lt; row; i++ ){
cout %26lt;%26lt; *(array+i) %26lt;%26lt; " ";
}
cout %26lt;%26lt; endl;
cout %26lt;%26lt; endl;
}
How do you use pointers with two dimensional arrays in C++?
Hi. I would love to help you. But, answering the question will be as long as your question. I thought that instead of giving a long answer, i could redirect you to some place where you can find good references.
http://www.cplusplus.com/doc/tutorial/
www.cplusplus.com/doc/tutorial/pointer...
www.codersource.net/c++_pointers.html
If you are still unable to find any useful information, and if there is anything specific that you would like to know, just drop in a mail to me. I shall try to help you.
Thanks! :)
Reply:u r goin right way baby
Reply:Generally speaking to access an array you use a for loop. This is for a 1 dimentional array. You want a two dimentional array.
So the way to do this is a nested for loop
ie.
for ( int i = 0; i %26lt; row; i++ ){
for ( int j = 0; j %26lt; col, j++ ){
cout %26lt;%26lt; "Enter an integer: ";
cin %26gt;%26gt; array[i][j];
}
}
That is all there is to it. You already understand the array concept. Now go ahead and extend what you know.
Good luck.
snow of june
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment