void takeTime(struct tm * timeNow)
{
time_t timeInSec;
time(&timeInSec);
timeNow = localtime(&timeInSec);
return;
}
int main()
{
struct tm* timeNow;
takeTime(timeNow);
printf("%s\n", asctime(timeNow));
return 0;
}
tried executing the code, but got Segmentation fault, can anyone explain why. i'm new to programming!
CodePudding user response:
Function localtime
returns a pointer to a statically allocated structure.
The code in the question modifies the local copy of the pointer timeNow
in takeTime
but the value is not returned to the caller.
If you want to pass the pointer to the caller you need to emulate a reference by using another level of indirection, i.e. a pointer to a pointer.
#include <stdio.h>
#include <time.h>
void takeTime(struct tm ** timeNow)
{
time_t timeInSec;
time(&timeInSec);
*timeNow = localtime(&timeInSec);
// This return at the end of a void function can be removed
// return;
}
int main(void)
{
struct tm* timeNow;
takeTime(&timeNow);
printf("%s\n", asctime(timeNow));
return 0;
}
Or you could want to get a copy of this structure. Then you need a structure variable in main
and have to pass its address.
#include <stdio.h>
#include <time.h>
void takeTime(struct tm * timeNow)
{
time_t timeInSec;
time(&timeInSec);
*timeNow = *localtime(&timeInSec);
// This return at the end of a void function can be removed
// return;
}
int main(void)
{
struct tm timeNow;
takeTime(&timeNow);
printf("%s\n", asctime(&timeNow));
return 0;
}
Or you could return the pointer
#include <stdio.h>
#include <time.h>
struct tm * takeTime(void)
{
time_t timeInSec;
time(&timeInSec);
return localtime(&timeInSec);
}
int main()
{
struct tm* timeNow;
timeNow = takeTime();
printf("%s\n", asctime(timeNow));
return 0;
}
Another variant of returning a structure and a more detailed explanation are shown in an Farhod Nematov's answer.