-2

In line 14 of specification file there are two parameters (pointers to char). the thing i have learned so far is that pointers store address of a variable by & operator but in the int main function on line # 8 direct strings are passed. is it correct to pass direct strings to pointer variable?

1 // Specification file for the Contact class.    
2 #ifndef CONTACTINFO_H    
3 #define CONTACTINFO_H    
4 #include <cstring> // Needed for strlen and strcpy    
5    
6 // ContactInfo class declaration.    
7 class ContactInfo    
8 {    
9 private:    
10 char *name; // The name    
11 char *phone; // The phone number    
12 public:    
13 // Constructor    
14 ContactInfo(char *n, char *p)    
15 { // Allocate just enough memory for the name and phone number.    
16 name = new char[strlen(n) + 1];    
17 phone = new char[strlen(p) + 1];    
18    
19 // Copy the name and phone number to the allocated memory.    
20 strcpy(name, n);    
21 strcpy(phone, p);     
22}    
23 // Destructor    
24 ~ContactInfo()    
25 { delete [] name;    
26 delete [] phone;     
27}    
28 const char *getName() const    
29 { return name; }    
30 const char *getPhoneNumber() const    
31 { return phone; }    
32 };    
33 #endif    


// main     

1 #include <iostream>    
2 #include "ContactInfo.h"    
3 using namespace std;    

4 int main()    
5 {    
6 // Define a ContactInfo object with the following data:    
7 // Name: Kristen Lee Phone Number: 555-2021    
8 ContactInfo entry("Kristen Lee", "555-2021");    
9    
10 // Display the object's data.    
11 cout << "Name: " << entry.getName() << endl;    
12 cout << "Phone Number: " << entry.getPhoneNumber() << endl;    
13 return 0;    
14 }
Subhan
  • 21
  • 3
  • 4
    String literals are a `const` array of `char`. When an array is passed as an argument to a function, the value passed is a pointer to the array's first element. – Peter Apr 21 '19 at 11:40
  • Why don't you use `std::string` and what is your goal? – Superlokkus Apr 21 '19 at 14:05

2 Answers2

0

When a literal string appears in your program, its value is actually a pointer to the first char of the string. So "Kristen Lee" is already a pointer (actually, an array; see here for some technical details).

The problem with literal strings is that they are read-only, so you should use const char* wherever you use them. In your constructor, you don't intend to change the input string anyway, so the declaration should be ContactInfo(const char *n, const char *p) regardless of whether you use literal strings.


Both char* and const char* are not so good for storage of strings, mostly because you have to delete them correctly when done. This is not easy! Instead of trying to do it, consider using std::string for storing strings.

anatolyg
  • 26,506
  • 9
  • 60
  • 134
-2

In C string (also arrays) is pointer type and have to be passed to functions with pointer arguments. & is used to getting the address of other types and casting to the pointer.