A. Sen
A. Sen

Reputation: 53

Printing a pointer to a pointer

This may be very simple but I am confused! I am getting segmentation fault when extracting information from a pointer to a pointer. See the cout section in main(). Any help will be appreciated.
Thanks..

Sen

#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;

}

Upvotes: 4

Views: 164

Answers (3)

Jay D
Jay D

Reputation: 3307

In main

It should be

Time *_time;

GetTime(&_time)

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

Upvotes: 1

Stephen Newell
Stephen Newell

Reputation: 7828

You're passing sometime by value, not by reference so it remains uninitialized. Change GetTime to the following:

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

Because you're creating an array of pointers, you can use array notation to access them during printing as well.

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

Upvotes: 4

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153792

Unless an argument is explicitly labelled as using a reference it is passed by value in C++. Thus, assigning to sometime in GetTime() has no effect on _time in main().

My strong advice is not to us explict memory allocation but use containers, e.g. std::vector<T>, instead. You'd still need to pass the container by refernence, however.

Upvotes: 2

Related Questions