PS_OracleNerd PS_OracleNerd - 1 year ago 77
C++ Question

C++ / Best practice to work with pointers

I finished a beginner course on udemy, but I always struggle with understanding pointers, I started many times and pointers crashed my curiosity for programming every time. Now I finally want to pass this border. The point of this question, while the instructor was creating a pointer of an object he allocated them like described here:

person* k = new person[3] ;

for (i=0;i<3;i++){
// Why did he create a new person and copy the object from a pointer?
// isn't this wastage of space or has it a good reason.
person a_person = k[i] ;
char *name = "Superman" ;
a_person.set_name(name, strlen(name)) ;
a_person.set_age(30) ;
a_person.describe() ;

// isn't this better? Directly using the pointer to access the memory
// our pointer is pointing and change the variables there?
char *surname = "Spiderman" ;
(k+i)->set_name(surname, strlen(name)) ;
(k+i)->set_age(10) ;


class person {

int length() ;
void get_addresses();
int getid() ;
void set_name(char *ptr_name, size_t bytes) ;
char* get_name() ;
int get_age() ;
void describe() ;
void set_age(int number) ;

char* name ;
int age ;
int id ;
size_t bytes = 30 ;
int get_unique() ;
int setid() ;

E: The course had other code, but somehow I have to try it, so I built this person class with some functions and char*.

Answer Source
  • Remember to manage the ownership of your pointer carefully. Pair your new with delete, and new[] withdelete[], or you may leak the resource.

  • Let smart pointer to help you to manage the ownership of pointer, check std::unique_ptr or std::shared_ptr.

  • Use const char* to hold literal string and so does in parameter type instead of char*.

  • That k[i] returned is an object, not pointer. k is initialized as an array of person in length 3. k[i] means to dereference the element of array at i position. I guess the instructor lost a & to bind the k[i] like person& a_person = k[i];

  • Try other learning resource.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download