Hello every one.I coded a program to print current date and time.
First I declare a function tim() to calculate the current time.
It works well.But the problem is I cant call the function from main() function.It doesnt print any thing.What is wrong with this code?
Please help me.Thanks very much!
here is my code.

#include<stdio.h>
#include<stdlib.h>
#include<time.h>

char* tim()
{
struct tm *d;
time_t now;
char li[50];
char* temp;

	time(&now);
	d=localtime(&now);
	memset(li,'\0',sizeof(li));
	strftime(li,50,"%Y.%m.%d.%H.%M.%S",d);
	temp =li;
//	printf("time now:%s\n",temp);	
	return temp;

}

int main()
{
char* array;
array=tim();
printf("Time:%s\n",array);

}

Recommended Answers

All 3 Replies

You return a variable that ceases to exist after the function all (a variable local to the called function). Generally speaking, pass a pointer (to the start of the array) and then modify it in the called function.

>You return a variable that ceases to exist after the function all (a
>variable local to the called function). Generally speaking, pass a
>pointer (to the start of the array) and then modify it in the called
>function.
Exactly. I know some other person could have given advice to return a pointer which has been dynamically allocated by using malloc. But then, such a advice would be inappropriate since it would lead to the overhead of free-ing the memory.

Hello every one.I coded a program to print current date and time.
First I declare a function tim() to calculate the current time.
It works well.But the problem is I cant call the function from main() function.It doesnt print any thing.What is wrong with this code?
Please help me.Thanks very much!
here is my code.

#include<stdio.h>
#include<stdlib.h>
#include<time.h>

char* tim()
{
struct tm *d;
time_t now;
char li[50];
char* temp;

    time(&now);
    d=localtime(&now);
    memset(li,'\0',sizeof(li));
    strftime(li,50,"%Y.%m.%d.%H.%M.%S",d);
    temp =li;
//  printf("time now:%s\n",temp);   
    return temp;

}

int main()
{
char* array;
array=tim();
printf("Time:%s\n",array);

}

end quote.

Again - within the space of 24 hours you ignore advice about formatting your code correctly, You are extremely lucky there are good folks on this forum who are still prepared to help you.

Since you missed it the last time - READ THIS POST:
http://www.daniweb.com/forums/thread93280.html

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.