1

So im currently trying to do the following

void testLibrary() {
    tBook book_1;
    book_1.author[MAX_STRING_LEN] = "Alvaro";
    book_1.id = 1;
    book_1.title[MAX_STRING_LEN] = "Prueba A";
    printf("%s", book_1.title);
}

But I wont get "Prueba A" on the console oputput. same goes if I try with book_1.author or with %d and book_1.id

Heres my tBook struct

#define MAX_STRING_LEN 100
typedef struct {
    char author[MAX_STRING_LEN];
    char title[MAX_STRING_LEN];
    int id;
} tBook;

Not sure why is it not working... maybe on C you initialize structs in a different way?

Raggaer
  • 3,244
  • 8
  • 36
  • 67

1 Answers1

4

You cannot assign string literals to arrays in C. The "fix" of adding square brackets after the array fixes the compile, but does something completely different.

You need to use strcpy instead to make your code work:

strcpy(book_1.author, "Alvaro");
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • @Alnitak No, `strncpy` is for something different ([great explanation of that point is here](http://stackoverflow.com/a/1258577/335858)). I wish I could recommend `strlcpy`, but it's not really all that portable. – Sergey Kalinichenko Apr 30 '16 at 23:03
  • Yes, `strlcpy` would be better given the missing `\0` that `strncpy` can cause - but I think the point that `strcpy` operations are potentially unsafe still bears mentioning – Alnitak Apr 30 '16 at 23:06
  • 1
    @Alnitak `strncpy` is also potentially unsafe – M.M Apr 30 '16 at 23:59
  • "fixes the compile" - the code is still a constraint violation and must produce compiler messages (and if those messages are warnings instead of errors it's time to change the compiler flags) – M.M May 01 '16 at 00:00
  • @M.M you mean because of the trailing `\0` not being copied if the length exactly equals the buffer size (as I already mentioned above) or something else? – Alnitak May 01 '16 at 00:04
  • 2
    Yes, you just trade one type of unsafety for another . IMO `strcpy` is easier to use correctly and so less error-prone – M.M May 01 '16 at 00:09