Tuesday, July 14, 2009

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

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

C++ Help..... Can an array contain values of different data types?
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.
Reply: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]=%26amp;a;


poin[1]=%26amp;b;


poin[2]=c;


cout%26lt;%26lt;*(int*)poin[0]; //type casting and printing


cout%26lt;%26lt;*(float*)poin[1]; //type casting and printing


cout%26lt;%26lt;(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.
Reply:not in c++, someother languages do allow it though
Reply:no an array cannot contain values of different data types.since an array is a collection of elements of homogeneous data type.


No comments:

Post a Comment

Post a Comment