English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

C++ Help..... Can an array contain values of different data types?

2007-04-22 16:08:36 · 4 answers · asked by test r 1 in Computers & Internet Programming & Design

4 answers

Technically no, however, you have the option of using the pointer data type so that each pointer in the array points to a different object that's been instantiated.

You would somehow need to know ahead of time what data types are associated with each index position.

Another option is to polymorphism if the objects are similar and can be derived from the same superclass or perhaps they simply have the same interface.

Another option is to use a variant data type that can represent these objects.

2007-04-22 16:29:18 · answer #1 · answered by Skeptic 7 · 1 0

no an array cannot contain values of different data types.since an array is a collection of elements of homogeneous data type.

2007-04-22 16:13:53 · answer #2 · answered by spu 1 · 0 0

Definition of array is "holding any number of data in the same data type with consecutive memory. So, we can't create an array with different number of data types. Because each element should have the equal memory size.

There are two to do like that
1) Create void pointer array with number of elements as you need. And we can give the address of the any type of variable to each element of array, Even we can user defined data type and user defined class variable
void *poin[10];
int a=1;
float b=2.56;
chat *c="yahoo answers";
poin[0]=&a;
poin[1]=&b;
poin[2]=c;
cout<<*(int*)poin[0]; //type casting and printing
cout<<*(float*)poin[1]; //type casting and printing
cout<<(char*)poin[2]; //type casting and printing
Length can be applied by user need
2) create a struct variable with different variable
struct exam
{
int rno;
char *name;
float avg;
}
struct exam e;
e.rno=10;
e.name="yahoo answers";
e.avg=68.52;
//in this way number of variable can be changed after allocating the struct variable

Try this if you have a doubt mail me. I will be with you regarding this.

2007-04-22 16:32:48 · answer #3 · answered by Anonymous · 0 0

not in c++, someother languages do allow it though

2007-04-22 16:25:24 · answer #4 · answered by nigel 3 · 0 0

fedest.com, questions and answers