question about C++ pointer

why have we used a pointer *strname as a parameter in Setinfo function.what if we do not use a pointer?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
1 #include <iostream>2  class Employee
3  {
4  public:    
5    char m_strName[25];    
6     int m_nID;    
7     double m_dWage;
8       
9          void SetInfo(char *strName, int nID, double dWage)    
10         {        
11            strncpy(m_strName, strName, 25);        
12          m_nID = nID;        
12             m_dWage = dWage; 
               }
  
        void Print()    
                    {        
                   using namespace std;        
                   cout << "Name: " << m_strName << "  Id: " << m_nID << "                  Wage: $" << m_dWage << endl;    }
                     };
            
      int main()
              {    
             Employee cAlex;    
            cAlex.SetInfo("Alex", 1, 25.00);             Employee cJoe;    
             cJoe.SetInfo("Joe", 2, 22.25);
             cAlex.Print();   
              cJoe.Print();
                 return 0;
                }
Think about these:
1. What is the purpose of that parameter?
2. How is the variable used within the function?
3. What would you use instead?


PS. The use C-style "strings" and arrays is not recommended, because C++ standard library offers much more convenient and safe alternatives.
char * strncpy ( char * destination, const char * source, size_t num )


Pointer is required in the strncpy function? so is it the reason using pointer?
you don't need the pointer in your example because you are only reading the value. If you
were writing to the string then the pointer would be necessary because it points to some memory outside of the function.

your example could get away with...
void SetInfo(char strName[], int nID, double dWage)
Last edited on
thx a lot
Topic archived. No new replies allowed.