I'm trying to print the time in ISO-8601 with decisecond precision.
YYYY-MM-DDThh:mm:ss.s
Here is my code:
#include <sys/time.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void milli_time(char* dest, struct timeval* t)
{
struct tm* timeInfo;
strftime(dest, 22, "%Y-%m-%dT%t", localtime(&t->tv_sec));
printf("%s\n", dest);
fflush(stdout);
char deciTime[3];
sprintf(deciTime, ".%lu", ((t->tv_usec)/100000ul));
strcat(dest, deciTime);
}
int main()
{
struct timeval* theTime;
char timeString[32];
gettimeofday(theTime, NULL);
printf("%lu.%lu\n", theTime->tv_sec, theTime->tv_usec);
milli_time(timeString, theTime);
printf("%s\n", timeString);
fflush(stdout);
}
And the output every time I run it is:
134520616.3077826840
1974-04-06T17:50:16
1974-04-06T17:50:16.30778
The other thing I notice is that tv_usec is greater than one million.
Change struct timeval* theTime to struct timeval theTime and update the corresponding references to it:
gettimeofday(&theTime, NULL);
// etc
This way you're allocating the space for the struct, rather than just a pointer to the struct. Your code segfaults when I try to run it on my machine.
Related
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.
I'm trying to write a data structure with two elements, and then defining a variable of that type struct. However, after initializing the variable in the main function, I'm getting segmentation fault and I don't know why.
#include <stdio.h>
#include <string.h>
struct AnimalSizes {
char stringName[50];
double sizeLength;
} animalSizes[2];
int main()
{
struct AnimalSizes *snakes;
strcpy(snakes[0].stringName,"Anaconda");
snakes[0].sizeLength=3.7;
strcpy(snakes[1].stringName,"Python");
snakes[1].sizeLength= 2.4;
printf("%c", *snakes[0].stringName);
printf("%lf", snakes[0].sizeLength);
printf("%c", *snakes[1].stringName);
printf("%lf", snakes[1].sizeLength);
return 0;
}
You try to strcpy to destination where is no allocated memory. That is undefined behavior.
You should first allocate enough memory to hold two AnimalSizes instances:
struct AnimalSizes *snakes;
snakes = malloc(2 * sizeof(struct AnimalSizes));
Also, here
printf("%c", snakes[0].stringName);
you are trying to output the first character of stringName. I assume, what you rather want to do is to output whole string with %s.
You've declared a pointer to a struct AnimalSizes, and you have declared an array struct AnimalSizes[2], but you have not made the pointer point to this array:
int main()
{
struct AnimalSizes *snakes = &animalSizes[0];
...
}
Alternatively, you may choose to not declare a global variable, rather choosing to allocate memory in main:
#include <stdlib.c>
#include <stdio.h>
#include <string.h>
struct AnimalSizes {
char stringName[50];
double sizeLength;
};
int main()
{
struct AnimalSizes *snakes = (struct AnimalSizes*) malloc(2*sizeof(struct AnimalSizes));
strcpy(snakes[0].stringName,"Anaconda");
snakes[0].sizeLength=3.7;
strcpy(snakes[1].stringName,"Python");
snakes[1].sizeLength= 2.4;
printf("%c", *snakes[0].stringName);
printf("%lf", snakes[0].sizeLength);
printf("%c", *snakes[1].stringName);
printf("%lf", snakes[1].sizeLength);
free(snakes);
return 0;
}
the following proposed code:
eliminates any need for malloc() and free()
performs the desired functionality
separates the definition of the struct from any instance of the struct.
inserts some spacing between the first letter of the snake name and the 'size' of the snake, for readability
applies certain other changes to the code for 'human' readability
and now the proposed code:
#include <stdio.h>
#include <string.h>
struct AnimalSizes
{
char stringName[50];
double sizeLength;
};
int main( void )
{
struct AnimalSizes snakes[2];
strcpy(snakes[0].stringName,"Anaconda");
snakes[0].sizeLength=3.7;
strcpy(snakes[1].stringName,"Python");
snakes[1].sizeLength= 2.4;
printf("%c ", snakes[0].stringName[0]);
printf("%lf\n", snakes[0].sizeLength);
printf("%c ", snakes[1].stringName[0]);
printf("%lf\n", snakes[1].sizeLength);
return 0;
}
a run of the proposed code outputs:
A 3.700000
P 2.400000
This question already has answers here:
Returning an array using C
(8 answers)
Closed 3 years ago.
I have my function print_date_time which I want to return the date as a string. I then want to assign that time to a new variable and print it in main. After that, I want to use it in another function.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <windows.h>
#include <time.h>
#include <assert.h>
static char* print_date_time()
{
time_t t = time(NULL);
struct tm* tm = localtime(&t);
char s[64];
assert(strftime(s, sizeof(s), "%c", tm));
//printf("TIME TIME: %s\n", s);
return s;
}
/****************************************
*
* MAIN FUNCTION
*
****************************************/
int main(int argc, char** argv)
{
char *date;
date = print_date_time();
printf("time is: %s\n",date);
//assert(strftime(tab, sizeof(tab), "%c", print_date_time()));
//print_date_time();
return 0;
}
I expect the current time.
How do I get a string from a function and assign to it?
char s[64] is stack allocated array and you are returning a pointer to this, which is undefined behaviour. Allocate s on heap instead.
int sz = 64 * sizeof(char);
char *s = malloc(sz);
assert(strftime(s, sz, "%c", tm));
I have a 'struct' which I would like to use in multiple sources files. I have declared the struct in the Header File and then have included in the sources files. It would be great if someone can assist me in this problem.
I am posting Header, Source and Error
#ifndef DATABASE_H
#define DATABASE_H
struct dataBase
{
char modelName;
float capacity;
int mileage;
char color;
};
extern struct dataBase Inputs;
#endif /* DATABASE_H */
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include "dataBase.h"
struct dataBase Inputs = NULL;
//size_t Inputs_Size = 0;
int main (void)
#include "hw4_asharma_display.h"
#include <stdio.h>
#include "dataBase.h"
void printLow(int size)
{
// Declaring Variables
int i;
for(i=0; i<size; i++)
{
printf("%s %f %d %s\n",
Inputs[i].modelName,
Inputs[i].capacity,
Inputs[i].mileage,
Inputs[i].color);
}
hw4_asharma_display.c:14:23: error: subscripted value is not an array, pointer, or vector
Inputs[i].modelName,
~~~~~~^~
hw4_asharma_display.c:29:23: error: subscripted value is not an array, pointer, or vector
Inputs[i].modelName,
Inputs is not an array, so you can't just use the [i] index notation. You'll have to change its declaration from:
struct dataBase Inputs = NULL;
(btw the NULL part is pointless) to
struct dataBase Inputs[N];
Instead, if you meant to have only one element, keep the declaration:
struct dataBase Inputs;
but remove the [i] part:
printf("%c %f %d %c\n",
Inputs.modelName,
Inputs.capacity,
Inputs.mileage,
Inputs.color);
Also, you will have to fill each element before printing or you will get all zeroes and blanks.
I can't understand why this code does not print current time in every one second.
What is the problem here ?
#include <stdio.h>
#include <unistd.h>
#include <time.h>
int main(int argc, const char * argv[])
{
while (1) {
sleep(1);
time_t tm;
struct tm *t_struct;
tm = time(NULL);
t_struct = localtime(&tm);
printf("%.2d:%.2d:%.2d", t_struct->tm_hour, t_struct->tm_min, t_struct->tm_sec);
}
return 0;
}
stdout may be line buffered, so you might need to either fflush it after outputting text, or print a newline to make changes visible.