Directly setting values of struct tm's attributes not working - c++

Why does asctime(ptr) return nothing? All the variables of the struct have values. Can someone explain why does this happen?
I also tried using strftime but the result was the same.
#include <iostream>
#include <ctime>
#include <new>
//#include <cstdio>
using namespace std;
int main(int argc,char *argv[])
{
struct tm *ptr=new struct tm;
//char buf[50];
ptr->tm_hour=0;
ptr->tm_mon=0;
ptr->tm_year=0;
ptr->tm_mday=0;
ptr->tm_sec=0;
ptr->tm_yday=0;
ptr->tm_isdst=0;
ptr->tm_min=0;
ptr->tm_wday=0;
cout << asctime(ptr);
//strftime(buf,sizeof(char)*50,"%D",ptr);
//printf("%s",buf);
return 0;
}

The below program works. Remove zero with 1 and it will work.
struct tm *ptr = new struct tm();
char buf[50];
ptr->tm_hour = 1;
ptr->tm_mon = 1;
ptr->tm_year = 1;
ptr->tm_mday = 1;
ptr->tm_sec = 1;
ptr->tm_yday = 1;
ptr->tm_isdst = 1;
ptr->tm_min = 1;
ptr->tm_wday = 1;
cout << asctime(ptr)
This also works:
ptr->tm_hour = 0;
ptr->tm_mon = 0;
ptr->tm_year = 0;
ptr->tm_mday = 1;
ptr->tm_sec = 0;
ptr->tm_yday = 0;
ptr->tm_isdst = 0;
ptr->tm_min = 0;
ptr->tm_wday = 0;
cout << asctime(ptr);

The behavior of asctime is undefined if any member of struct tm is outside its normal range.
Especially the behavior is undefined if the calendar day is less than 0 (some implementations handle tm_mday==0 as meaning the last day of the preceding month).
Take a look at http://en.cppreference.com/w/cpp/chrono/c/asctime and http://en.cppreference.com/w/cpp/chrono/c/tm for further details.

Related

How to fill a String inside an array of structures within a structure in C++

So I have a structure called fastarray which contains a poiner to another structure called token_det. My problem is trying to fill a char array inside the array of structs fails mid way through and gives a error message as "The exception unknown software exception (0x0000417) occured in the application at location 0x78b2ae6e". I tried increasing the size of the char array using malloc but the string concat function keeps failing after concatinating a few strings. Below is a example of the code:
#include <stdio.h>
#include <string>
#include <stdlib.h>
#include <iostream.h>
using namespace std;
#define MAX_TOKENS 300000
struct token_det
{
int token;
std::string data;
char mdepth[300];
};
typedef struct fastarray
{
token_det *td; //MAX_TOKENS
}FASTARRAY;
int main()
{
printf("inside main\n");
int lv_ret = 0;
int count = 0;
char log[50] = {""};
int wtoken = 0;
FASTARRAY *f_array = NULL;
f_array = (FASTARRAY *)malloc(sizeof(FASTARRAY));
f_array->td = NULL;
f_array->td = (token_det *)malloc(MAX_TOKENS * sizeof(token_det));
printf("after malloc\n");
memset(f_array, 0, sizeof(f_array));
memset(f_array->td, 0, sizeof(f_array->td));
int x=0;
while(x<=10000)
{
printf("inside while");
f_array->td[x].data = "104,";
f_array->td[x].data.append("stasimorphy");
f_array->td[x].data.append(",");
f_array->td[x].data.append("psychognosy");
f_array->td[x].data.append(",");
f_array->td[x].data.append("whoever");
f_array->td[x].data.append(",");
x++;
sprintf_s(log,sizeof(log),"Data for x-%d = %s\n",x,f_array->td[x].data);
printf(log);
}
free(f_array->td);
free(f_array);
printf("after while\n");
return 0;
}
Explanation of what I was doing and why
When I tried to understand what you wanted to do there I've had no problem except for the parts in which you're using memset. With memset(f_array, 0, sizeof(f_array)); you're explicitly setting the f_array to point to 0 in the memory which was constantly throwing exceptions for me.
As I've never really been a friend of malloc I've been using C++ syntax as follows:
For allocating a single instance I'd use FASTARRAY *f_array = new fastarray;. You can read up on why using new instead of malloc is favorable in C++ here.
In the same way I've been using C++ syntax for allocating the dynamic array f_array->td = new token_det[MAX_TOKENS]; A Q&A about that topic for reference can be found here.
For filling the data string inside the dynamic array's struct I've been using the += syntax as it's easier to read, in my opinion. Accessing the element inside the f_array has been achieved using (*(f_array->td + x)).data += "stasimorphy";
You can try my solution online here.
Code Dump
I tried to change as little as possible to make it work.
#include <sstream>
#include <string>
#include <iostream>
using namespace std;
#define MAX_TOKENS 300000
struct token_det
{
int token;
std::string data;
char mdepth[300];
};
typedef struct fastarray
{
token_det *td; //MAX_TOKENS
}FASTARRAY;
int main()
{
std::cout << "inside main\n";
int lv_ret = 0;
int count = 0;
char log[50] = { "" };
int wtoken = 0;
FASTARRAY *f_array = new fastarray;
f_array->td = new token_det[MAX_TOKENS];
std::cout << "after malloc\n";
int x = 0;
while (x <= 10000)
{
std::cout << "inside while";
std::stringstream log;
(*(f_array->td + x)).data = "104,";
(*(f_array->td + x)).data += "stasimorphy";
(*(f_array->td + x)).data += ",";
(*(f_array->td + x)).data += "psychognosy";
(*(f_array->td + x)).data += ",";
(*(f_array->td + x)).data += "whoever";
(*(f_array->td + x)).data += ",";
log << "Data for x-" << x << " = " << (f_array->td + x)->data << std::endl;
std::cout << log.str();
x++;
}
delete[] f_array->td;
free(f_array);
std::cout << "after while\n";
return 0;
}

'future' has been explicitly marked deleted here

I am trying to build a Async application to allow processing of large lists in parallel, and after two days of learning C++ through googling I have come up with the title error, from the following code:
//
// main.cpp
// ThreadedLearning
//
// Created by Andy Kirk on 19/01/2016.
// Copyright © 2016 Andy Kirk. All rights reserved.
//
#include <iostream>
#include <thread>
#include <vector>
#include <chrono>
#include <future>
typedef struct {
long mailing_id;
char emailAddress[100];
} emailStruct ;
typedef struct {
long mailing_id = 0;
int result = 0;
} returnValues;
returnValues work(emailStruct eMail) {
returnValues result;
std::this_thread::sleep_for(std::chrono::seconds(2));
result.mailing_id = eMail.mailing_id;
return result;
}
int main(int argc, const char * argv[]) {
std::vector<emailStruct> Emails;
emailStruct eMail;
// Create a Dummy Structure Vector
for (int i = 0 ; i < 100 ; ++i) {
std::snprintf(eMail.emailAddress,sizeof(eMail.emailAddress),"user-%d#email_domain.tld",i);
eMail.mailing_id = i;
Emails.push_back(eMail);
}
std::vector<std::future<returnValues>> workers;
int worker_count = 0;
int max_workers = 11;
for ( ; worker_count < Emails.size(); worker_count += max_workers ){
workers.clear();
for (int inner_count = 0 ; inner_count < max_workers ; ++inner_count) {
int entry = worker_count + inner_count;
if(entry < Emails.size()) {
emailStruct workItem = Emails[entry];
auto fut = std::async(&work, workItem);
workers.push_back(fut);
}
}
std::for_each(workers.begin(), workers.end(), [](std::future<returnValues> & res) {
res.get();
});
}
return 0;
}
Really not sure what I am doing wrong, and have found limited answers searching. Its on OSX 10 if that is relevant, and XCode 7.
The future class has its copy constructor deleted, because you really don't want to have multiple copies of it.
To add it to the vector, you have to move it instead of copying it:
workers.push_back(std::move(fut));
This error can also be raised if you are passing a future object (within a thread) to a function which expects a pass by value.
For example, this would raise an error when you pass the future:
void multiplyForever(int x, int y, std::future<void> exit_future);
multiplyForever(3, 5, fut);
You can fix it by passing the future by reference:
void multiplyForever(int x, int y, std::future<void>& exit_future);
multiplyForever(3, 5, fut);

Digital clock c++

Making a digital clock in c++ and I get these errors:
expected ; before reloj
statement is a reference, not call, to funcion 'time'
statement has no effect
''reloj'' is undeclared (first use this function)
Each undeclared identifier is reported only once for each function it appears
#include<iostream>
#include<Windows.h>
using namespace std;
struct time
{
int hr,mint,seg;
};
int main()
{
time reloj;
reloj.hr = 0;
reloj.mint = 0;
reloj.seg = 0;
for(int i = 0; i<24; i++)
{
if(reloj.hr == 23)
{
reloj.hr = 0;
}
for(int j = 0; j<60; j++)
{
if(reloj.mint == 59)
{
reloj.mint = 0;
}
for(int k = 0; k<60; k++)
{
if(reloj.seg == 59)
{
reloj.seg = 0;
}
cout<<reloj.hr<<" : "<<reloj.mint<<" : "<<reloj.seg<<endl;
reloj.seg++;
Sleep(1000);
system("Cls");
}
reloj.mint++;
}
reloj.hr++;
}
}
using namespace std; in the global namespace is a bad idea, and is probably dumping std::time there, along with a host of other names. This will clash with your time class.
Unfortunately, simply removing the evil using isn't a solution here, since time comes from the C library. Implementations are allowed to (and many do) dump names from the C library into the global namespace whether you want them there or not.
So your options are:
Rename your class, or put it in your own namespace;
Refer to it as struct time rather than just time;
Don't include any standard library headers, just in case they mess with your global names.
I have Another codes :
#include <iostream>
#include <unistd.h>
#include <ctime>
using namespace std;
void Timer()
{
int HOUR = 0, MINUTE = 0 , SECOND = 0;
time_t now = time(0);
tm *ltm = localtime(&now);
HOUR = ltm->tm_hour;
MINUTE = ltm->tm_min;
SECOND = ltm->tm_sec;
while(true)
{
system("clear");
cout << HOUR << ":" << MINUTE << ":" << SECOND << endl;
SECOND ++;
if(SECOND == 60)
{
MINUTE++;
SECOND = 0;
if(MINUTE == 60);
{
HOUR++;
MINUTE = 0;
if(HOUR ==24)
{
HOUR = 0;
}
}
}
sleep(1);
}
}
int main()
{
Timer();
}
*IF YOU USE THIS ON WINDOWS THEN CHANGE system("clear") into system("cls")

Pointers and structures

I'm trying to wrap my head around pointers, references and addresses but every time I think I got it something unexpected pops up.
Why don't we need to dereference the structure to set a value in this example?
// pointer_tet.cpp
#include <iostream>
struct example
{
char name[20];
int number;
};
int main()
{
using namespace std;
example anExample = {"Test", 5};
example * pt = &anExample;
pt->number = 6;
cout << pt->number << endl;
int anotherExample = 5;
int * pd = &anotherExample;
*pd = 6;
cout << *pd << endl;
return 0;
}
Thanks!
Edit: Thank you for your answers! What confused me was not being able to set *pt.number = 6.
You are dereferencing pt. You are doing:
pt->number = 6;
This is equivalent to:
(*pt).number = 6;
The -> operator provides a convenient way to access members through a pointer.
You can do
anExample.number = 6;
OR
(*pt).number = 6;
Read cplusplus.com pointer tutorial might help.

converting int to pointer

I want to save int value to a pointer variable. But I get an error:
#include <iostream>
using namespace std;
int main()
{
int *NumRecPrinted = NULL;
int no_of_records = 10;
NumRecPrinted = (int*)no_of_records; // <<< Doesn't give value of NumRecPrinted
cout << "NumRecPrinted!" << NumRecPrinted;
return 0;
}
I tried doing this but I get 0 as return:
int main()
{
int demo(int *NumRecPrinted);
int num = 2;
demo(&num);
cout << "NumRecPrinted=" << num; <<<< Prints 0
return 0;
}
int demo (int *NumRecPrinted)
{
int no_of_records = 11;
NumRecPrinted = &no_of_records;
}
NumRecPrinted returns as 0
It's sometimes useful to "encode" a non-pointer value into a pointer, for instance when you need to pass data into a pthreads thread argument (void*).
In C++ you can do this by hackery; C-style casts are an example of this hackery, and in fact your program works as desired:
#include <iostream>
using namespace std;
int main()
{
int *NumRecPrinted = NULL;
int no_of_records = 10;
NumRecPrinted = (int*)no_of_records;
cout << "NumRecPrinted!" << NumRecPrinted; // Output: 0xa (same as 10)
return 0;
}
You just need to realise that 0xa is a hexadecimal representation of the decimal 10.
However, this is a hack; you're not supposed to be able to convert ints to pointers because in general it makes no sense. In fact, even in the pthreads case it's far more logical to pass a pointer to some structure that encapsulates the data you want to pass over.
So, basically... "don't".
You want to be doing this:
NumRecPrinted = &no_of_records;
i.e. you're taking the address of no_of_records and assigning it to NumRecPrinted.
And then to print it:
cout << "NumRecPrinted!" << *NumRecPrinted;
i.e. you're dereferencing NumRecPrinted which will get the int stored at the memory address pointed to by NumRecPrinted.
#include <iostream>
using namespace std;
int main()
{
int *NumRecPrinted = NULL; // assign pointer NumRecPrinted to be valued as NULL
int *NumRecPrinted2 = NULL;
int no_of_records = 10; // initialize the value of the identificator no_of_records
NumRecPrinted = (int*)no_of_records; // sets a pointer to the address no_of_records
NumRecPrinted2 = &no_of_records; // gives a pointer to the value of no_of_records
cout << "NumRecPrinted!" << NumRecPrinted; // address of no_of_records 0000000A
cout << "NumRecPrinted!" << *NumRecPrinted2; // value of no_of_records 10
system("pause"); // ninja
return 0;
}
Here is the corrected version:
#include <iostream>
using namespace std;
int main()
{
int *NumRecPrinted = NULL;
int no_of_records = 10;
NumRecPrinted = &no_of_records; // take the address of no_of_records
cout << "NumRecPrinted!" << *NumRecPrinted; // dereference the pointer
return 0;
}
Note the added ampersand and the asterisk.
(int *)no_of_records gives you a pointer to the address no_of_records. To get a pointer to the value of no_of_records, you need to write &no_of_records.
I really like using union for this sort of stuff:
#include <iostream>
using namespace std;
int main()
{
static_assert(sizeof(int) == sizeof(int*));
union { int i; int* p; } u { 10 };
cout << "NumRecPrinted! " << u.p;
return 0;
}