Hello, I have this code that supposedly imitate a DTR for a homework. I've made the preliminary code, but I'm kinda surprised at the output since it's not what I had expected. Here's the code:

int login()
{
    int id;
    char* name, log_time;
    time_t lt;
    lt = time(NULL);
    
    printf("\nPlease enter your ID: ");
    scanf("%d", &id);
    
    if ( (id < NUMOFEMPLOYEES) &&  (id >= 0) )
    {
        name = names[id];
        printf("\n%d) %s ",login_counter, name);
        
        printf("%s", (char* )asctime(localtime(&lt)));
        login_times[login_counter] = (char* )asctime(localtime(&lt));
        login_records[login_counter] = id;
        login_counter++;
        system("PAUSE");
    } else
    {
        printf("INVALID ID.\n");
        system("PAUSE");
    }
    
    return 0;
}

and when I iterate through login_times, all of them have the same time value. no other part of the code operates on the array but this snippet. What could be wrong? Is the string stored in the array changing too?

Thanks for the help, everyone.^^

>> when I iterate through login_times, all of them have the same time value

asctime() uses a single static buffer and returns a pointer to this buffer every time you call it. In other words, all pointers that you store in the login_times array, point to the very same location in memory - hence the behaviour.

How about storing the time_t values inside the login() function and only use localtime()/asctime() when you need a string representation of the times? I.e.

/* Somewhere you'd have ... */
time_t login_times[NUMOFEMPLOYEES] = {0};

int login()
{
  ...    

  scanf("%d", &id);

  if ( (id < NUMOFEMPLOYEES) &&  (id >= 0) )
  {
    ...

    /* Store the time of login ... */
    login_times[login_counter] = time(NULL);
    ...

and use later ..

printf("login time: %s\n", asctime(localtime(&login_times[ <some valid index here> ])));

ahh, brilliant! I will try this out! Thanks.:D

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.