I want to put the following data into a array
ID Name Gender
FD4564 Mary F
IU4564 Peter M
ER4567 John M
How to create a 3D array in C language?
#include %26lt;stdio.h%26gt;
char array3d[][10][10] =
{
{"ID", "Name", "Gender"},
{"FD4564", "Mary", "F"},
{"IU4564", "Peter", "M"},
{"ER4567", "John", "M"}
};
int main()
{
for(int i=0; i%26lt;4; i++)
{
for(int j=0; j%26lt;3; j++)
{
printf("\t%s\t", array3d[i][j]);
}
printf("\n");
}
return 0;
}
Reply:Why not create a struct and populate an array with them?
struct Person
{
int id;
string name;
bool isMale;
}
Person *people = new Person[10];
Reply:I don't think you need a 3D array for this. Are you ever going to need to access something like this:
FD4564 Mary F
FD4564 Mary M
FD4564 Mary M
That doesn't make sense in this context. Use the struct and use char* str = new char[...] if you need variable length strings. Also if the dimensions of the array are going to change frequently, you need a different data structure (linked list).
If you really need to do it this way, then do this:
char* ** array = new char**[X];
for(i=0; i%26lt;X; i++)
{
array[i] = new char*[Y];
}
array[0][0] = "FD4564";
array[0][1] = "Mary";
array[0][2] = "F";
where X and Y are rows and columns, respectively.
Reply:Just initialize 3 different indices to point ID, Name, Gender respectively...
#include%26lt;stdio.h%26gt;
main()
{
int id, name, gender, arr[5][5][5] ;
....
....
for( id=0;id%26lt;cnt1;id++ )
{
for( name=0;name%26lt; cnt2; name++ )
{
for(gender=0;gender%26lt;cnt3;gender++ )
{
.....
..... // scan inputs from user ...
}}}
getch() ;
}
Reply:I would create a struct unless you have been explicitly told that you need to use a 3D array.
petal
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment