Printing a pointer to a pointer

It may be very simple, but I'm confused! I get a segmentation error when retrieving information from pointer to pointer. See the cout section in main (). Any help would be appreciated. Thanks..

Sep

#include <stdlib.h> #include <iostream> typedef struct{ int hour; int minute; } Time; Time* GetNextTime(void) { Time *p_time = new Time; return p_time; } void GetTime( Time **sometime ) { int length = 10; sometime = new Time*[length]; for(int i=0; i<length; i++) { sometime[i] = GetNextTime(); sometime[i]->hour = rand()%24 ; sometime[i]->minute = rand()%60; std::cout << "Entered times " << sometime[i]->hour << " hour " << sometime[i]->minute << " minutes " << std::endl; } } int main() { Time** _time; GetTime( _time ); //here is the question // I cant print them from original _time for( int i=0; i<10; i++) std::cout << " Print times " << (*_time)[i].hour << " hour " << (*_time)[i].minute << " minutes " << std::endl; } 
+4
source share
3 answers

You pass sometime by value, not by reference, so that it remains uninitialized. Change GetTime to the following:

 void GetTime( Time ** &sometime ) //& means pass by reference 

Since you are creating an array of pointers, you can use array notation to access them while printing. A.

 std::cout << " Print times " << _time[i]->hour << " hour " << _time[i]->minute << " minutes " << std::endl; 
+4
source

If the argument is not explicitly marked as using the link, it is passed by value in C ++. Thus, assigning sometime to GetTime() does not affect _time in main() .

My strong advice is not that we disclose memory allocation, but use containers, for example. std::vector<T> . However, you still need to pass the container by reference.

+2
source

In main

It should be

Time *_time;

GetTime(&_time)

And then cout should be done using _time instead of *_time

+1
source

Source: https://habr.com/ru/post/1412206/


All Articles