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) ;
(k+i)->describe();
}
class person {
public:
person();
~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) ;
private:
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*.
E2: yes, in the advanced c++ are all these structures, vectors, lists, maps and many c++11 features mentioned
In first case you r creating a new object and copying data from object in array. In such way you r working with 'a_person' object, not with object in array. In second case you are working with objects in array.
Remember to manage the ownership of your pointer carefully. Pair your new
with delete
, and new[]
with delete[]
, 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.