2

Let me preface with my c background is about as deep as a puddle in the desert.

I'm trying to create a struct that has this format:

struct Event {
    char time[20];
    char name[20];
    char userId[20];
}; 

Then assign the values like this:

int main(int argc, const char * argv[]) {

    struct Event event1;

    strcpy( event1.time, "2007-03-01T13:00:00Z");
    strcpy( event1.name, "VS");
    strcpy( event1.userId, "2d97f036a1T13G21Jm0Z");

    printf("%s", event1.time);

    return 0;
}

However, I'm getting SIGABRT on this line:

strcpy( event1.time, "2007-03-01T13:00:00Z");

Which makes sense because of the number values in the timestamp. I can't seem to find anything on how to store both numbers and characters in string.

6
  • 8
    char time[20]: not enough bytes to hold a 20-byte string. You forgot the trailing zero. Sep 8, 2016 at 15:39
  • Ah! like I said, my C knowledge is absolutely 0. No wonder googling "chars and ints" in a string didn't return anything :P
    – random
    Sep 8, 2016 at 15:44
  • 4
    What do you mean by "store both numbers and characters in string"? What do you think is happening, or should happen? Your string stores only characters, even if some of those characters represent a number (as text)...
    – Dmitri
    Sep 8, 2016 at 15:44
  • the \0 character also needs one place. So, I think changing char time[20] to char time[21] can solve the problem. Sep 8, 2016 at 15:45
  • 1
    Also, make sure you #include <string.h> for strcpy()
    – Dmitri
    Sep 8, 2016 at 15:46

1 Answer 1

1

The first thing I see is that 2007-03-01T13:00:00Z and 2d97f036a1T13G21Jm0Z requires char [21] to allow for the additional \0 terminating character.

Not sure why you are getting the failure on event1.time as it should overflow into the next field, but try fixing the field sizes and retest.

FYI: I've mostly given up on strcpy() for safety purposes and use strncpy() instead. In paranoid mode this looks like:

strncpy( target, source, sizeof target );
target[sizeof target - 1]] = '\0';   /* assure \0 terminator */

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.