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!
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 were shown in an Farhod Nematov's answer, which unfortunately has been deleted.
Related
#include<stdio.h>
#include<stdlib.h>
//structure defined
struct date
{
char day[10];
char month[3];
int year;
}sdate;
//function declared
void store_print_date(struct date *);
void main ()
{
struct date *datePtr = NULL;
datePtr = &sdate;
store_print_date(datePtr); // Calling function
}
void store_print_date(struct date *datePtr)
{
datePtr->day = "Saturday"; // error here
datePtr->month = "Jan"; // same here
datePtr->year = 2020;
}
You need to use strcpy() method to copy the string into the character array (note the comments):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// structure defined
struct date
{
char day[10];
char month[4]; // +1 size 'cause NULL terminator is also required here
int year;
} sdate;
// function declared
void store_print_date(struct date *);
int main(void) // always return an integer from main()
{
struct date *datePtr = NULL;
datePtr = &sdate;
store_print_date(datePtr); // Calling function
return 0;
}
void store_print_date(struct date *datePtr)
{
strcpy(datePtr->day, "Saturday"); // using strcpy()
strcpy(datePtr->month, "Jan"); // again
datePtr->year = 2020; // it's okay to directly assign since it's an int
printf("%s\n", datePtr->day); // successful
printf("%s\n", datePtr->month); // output
}
It'll display:
Saturday // datePtr->day
Jan // datePtr->month
I am new in C and literally trying to return pointer from my function to the pointer variable and have this "[Warning] assignment makes pointer from integer without a cast" no idea why compiler defines it as an int.
Can't declare my function before main as well, it throws this "undefined reference to `free_block'".
#include <stdio.h>
#include <stdlib.h>
struct block{
int num;
};
int main(int argc, char *argv[]) {
struct block *b;
b = free_block();
struct block *free_block(){
struct block *b = NULL;
return b;
}
return 0;
}
Thank you
Yea, my fault I know not too much about c syntax and had no idea about nested functions, soz.
But what could be wrong in this case:
I am trying to make my own memory allocator without using malloc or calloc functions. In my code I have the same Warning on the line with pointer = free_space_get(size);, here I have no more nested func(), my methods defined before main(), but still have no idea do I have to declare my functions or no, coz in the answer given to me it worked fine as soon as functions were defined before the main().
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct header{
size_t size;
struct header *next;
unsigned int free;
};
void *m_alloc(size_t size){
size_t total_size;
void *block;
struct header *pointer;
if(!size)
return NULL;
pointer = free_space_get(size);
if(pointer){
pointer->free = 0;
return (void*)(pointer + 1);
}
}
struct header *get_free_space(size_t size){
struct header *b = NULL;
return b;
}
int main() {
return 0;
}
Your code can be re-written as
#include <stdio.h>
#include <stdlib.h>
struct block{
int num;
};
struct block *free_block(){
struct block *b = NULL;
return b;
}
int main(int argc, char *argv[]) {
struct block *b;
b = free_block();
if(b == NULL) // Checking whether pointer is returned
printf("\n Recieved NULL \n");
return 0;
}
I have to display date and time separately using gettime() and getdate() in C programming language. The code I have written only displays date and time on same line. I want this code to be done using only core C not in a windows format.The editor I am using is Visual Studio 2008
Below I have post my code which only shows date time on a single line.
#include "stdafx.h"
#include <conio.h>
#include <stdio.h>
#include <time.h>
char *gettime();
int_main(int argc,_TCHAR* argv[])
{
printf("The time is %s\n",gettime());
getch();
return 0;
}
char *gettime()
{
time_t t;
tm b;
time(&t);
return ctime(&t);
}
You can use localtime/gmtime
struct tm * timeinfo;
timeinfo = localtime (&t);
And work with tm structure components as you need, also you can use strfrtime format function if you need only print date and time.
Main function is the same for all the different ways:
#include <stdio.h>
#include <time.h>
#include <string.h>
char * gettime();
char * getdate();
int main()
{
printf("The time is %s\n", gettime());
printf("The date is %s\n", getdate());
return 0;
}
One way you could do it is with manipulating the strings coming back from ctime() function. We know they are built in a similar way, the 1st 12 chars are week-day, month, month-day, then comes 8 chars of time, then finally the year. You could create functions like this:
char * gettime()
{
time_t t;
//use static so not to save the var in stack, but in the data/bss segment
//you can also make it a global scope, use dynamic memory allocation, or
//use other methods as to prevent it from being erased when the function returns.
static char * time_str;
time(&t);
time_str = ctime(&t) + 11;
time_str[9] = 0; //null-terminator, eol
return time_str;
}
char * getdate()
{
time_t t;
static char * date_str;
static char * year;
time(&t);
date_str = ctime(&t) + 4;
date_str[6] = 0;
year = date_str + 15;
year[5] = 0;
strcat(date_str, year);
return date_str;
}
The second way to do this is using localtime() function to create a tm-struct, and then extract what you need from it.
char * gettime()
{
time_t t;
struct tm *info;
static char time_str[10];
time(&t);
info = localtime(&t);
sprintf(time_str,"%d:%d:%d",(*info).tm_hour, (*info).tm_min, (*info).tm_sec);
return time_str;
}
char * getdate()
{
time_t t;
struct tm *info;
static char date_str[12];
time(&t);
info = localtime(&t);
sprintf(date_str,"%d/%d/%d",(*info).tm_mday, (*info).tm_mon+1, (*info).tm_year+1900);
return date_str;
}
You can make it a bit more clean using the strftime() function:
char * gettime()
{
time_t t;
struct tm *info;
static char time_str[10];
time(&t);
info = localtime(&t);
strftime(time_str, 10, "%S:%M:%H",info);
return time_str;
}
char * getdate()
{
time_t t;
struct tm *info;
static char date_str[12];
time(&t);
info = localtime(&t);
strftime(date_str, 12, "%d:%m:%Y",info);
return date_str;
}
I have the following SSCCE:
#include <stdio.h>
#include <stdint.h>
#include <time.h>
#include <string.h>
#define streq(x, y) (strcmp((x), (y)) == 0)
#define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0]))
typedef struct
{
const char *cmd;
void* (*fn)(void);
} __attribute__((__packed__)) Command;
void* getTime(void)
{
return ((void*)((uintptr_t)time(NULL)));
}
void* getDay(void)
{
time_t t = time(NULL);
struct tm tm = *localtime(&t);
return ((void*)((uintptr_t)(tm.tm_wday)));
}
static Command commands[] =
{
{"time", getTime},
{"day", getDay},
};
int main(int argc, char *argv[])
{
for (int i = 0; i < ARRAY_SIZE(commands); ++i)
{
Command *p = commands+i;
if (streq(argv[1], p->cmd)) printf("%d\n", (int)p->fn);
}
}
My question is why when I run the code as such:
./test day
The return value is 3648 and not a value from 0-6 as specified here.
You need to call the function. Right now you're just printing the function pointer value. The following code should do it:
if (streq(argv[1], p->cmd)) printf("%d\n", (int)(p->fn()));
I'm passing function GetCurrentDate() the pointer to a tm struct. Within that function I printf the uninitialized data, then the initialized. Expected results.
However when I return the tm struct appears uninitialized. See console output below. What am I doing wrong?
uninitialized date:??? ???-1073908332
01:9448278:-1073908376 -1217355836
initialized date:Wed May 5 23:08:40
2010
Caller date:??? ???-1073908332
01:9448278:-1073908376 -121735583
int main()
{
test();
}
int test()
{
struct tm* CurrentDate;
GetCurrentDate(CurrentDate);
printf("Caller date:%s\n",asctime (CurrentDate));
return 1;
}
int GetCurrentDate(struct tm* p_ReturnDate)
{
printf("uninitialized date:%s\n",asctime (p_ReturnDate));
time_t m_TimeEntity;
m_TimeEntity = time(NULL); //setting current time into a time_t struct
p_ReturnDate = localtime(&m_TimeEntity); //converting time_t to tm struct
printf("initialized date:%s\n",asctime (p_ReturnDate));
return 1;
}
You are updating the pointer p_ReturnDate in the function, not updating the structure that p_ReturnDate points to. Because the pointer is passed by value, the update doesn't affect the caller.
Also as pointed out by Joseph Quinsey you need to provide a place to put the result. You're only allocating a pointer in the caller, not the whole structure.
In test(), you need to actually specify memory to store the data. For example;
struct tm CurrentDate;
GetCurrentDate(&CurrentDate);
printf("Caller date:%s\n",asctime(&CurrentDate));
int
main()
{
test();
}
void
test()
{
struct tm CurrentDate;
GetCurrentDate(&CurrentDate);
printf("Caller date:%s\n", asctime(&CurrentDate));
}
void
GetCurrentDate(struct tm* p_ReturnDate)
{
time_t m_TimeEntity;
printf("uninitialized date:%s\n", asctime(p_ReturnDate));
m_TimeEntity = time(NULL); //setting current time into a time_t struct
*p_ReturnDate = *localtime(&m_TimeEntity); //converting time_t to tm struct
printf("initialized date:%s\n", asctime (p_ReturnDate));
}