+ 2
How to assign value of single dimensional array to two dimensional array.
I'm not able to figure out how to setup my loop so that I can able to assign my value from single dimensional array to two dimensional array. If anyone have any idea please let me know. Thank you.
6 Antworten
+ 5
in c/c++ the multidimensional array is just a syntactic sugar ..in reality its really a single dimensional array ..so what you can do is cast that single dimensional array to 2d array that way you dont even need any loops ...
an example :
#include <iostream>
using namespace std;
int main() {
int arr[4] = {
0, 1,
2, 3
};
int (*mult)[2]=(int(*)[2])arr;
cout << mult[0][0] << endl
<< mult[0][1] << endl
<< mult[1][0] << endl
<< mult[1][1] << endl;
return 0;
}
+ 1
For that your 1-d matrix have to n*m values to form n×m 2d- matrix.
And just let me know how you assign values normally into 2d array..
Normally we do cin>>arr[I][j] ;
instead do arr[I][j]= arr1d[k++] ; where I,j are index values for 2d array ,and k for 1d array.
Hope it helps..
+ 1
Jayakrishna🇮🇳 Omg thank you so much! It worked!
+ 1
Prashanth Kumar [back again] Thank you! It's really helpful
0
You're welcome Tushar Kumar
0
2D array consists of two things rows and columns. So it is 2D, one dimension array consists only by rows while it is one line with many elements. In 2D array you need two loops for rows and columns. Rows loop is outer and columns loop is nested. After loops follows condition statement (if sentence) then output statement. And at last you need again cout statement with endl, so it makes your array into columns.