lundi 30 mars 2015

passing a string to a function using character pointer

hey guys please have a look at this code.



class person
{
char name[20];
float age;

public:
person(char *s,float a)
{
strcpy(name,s);
age=a;
}
};

int main()
{
person P1("John",37.50);
person p2("Ahmed",29.0);
}


So in this class,the parametrized constructor takes a character pointer as an argument,and then passes the same to the strcpy function which copies the string to the character array name. If there is an integer array,like int arr[10]; then arr is a pointer to the first element. If there is a character array that is a string,like char str[]="Hello"; then str is a pointer to the first element,h in this case.So shouldn't we be passing something like str to the constructor?Why are we passing the character array elements,like "john","ahmed" to the constructor. Shouldn't we be doing - char str[]="ahmed"; person p1=(str,23);


Aucun commentaire:

Enregistrer un commentaire