JNeill
JNeill

Reputation: 11

Strcpy() array declaration?

I made this to just seal in strcpy() to my brain, and I noticed that if I leave the brackets empty the compiler says it needs an initializer or needs a specified value to compile. However I can put any value into the brackets and it still compiles. Even with a zero... But if the strcpy() function adds a string terminator to whatever string is declared, why would I still need to put a placeholder in the brackets?

Code below...

#include <stdio.h>
#include <string.h>

main()
{
    char yearFirst[0];  <------ HOW DOES THIS still EXECUTE??
    char yearSecond[6];
    char month[5];

    /* when declaring strcpy function, place each copied string before.
     their desired print function.
    or else the print function will print thr same strcpy for each print 
    function proceeding it.

    ex.
      strcpy(yearFirst, "Sept., Oct., Nov., Dec., Jan.");
      strcpy(yearSecond, "Mar., Apr., May., Jun. Jul., Aug.");
      followed by:
        printf("These months have 1-31 days: %s\n\n", yearFirst)
        printf("These months have 1-30 days: %s\n\n", yearSecond);

    output will equal both statements saying
    "These months have 1-31: sept oct ...."
    "these months have 1-30: sept oct....."
    */ 

    strcpy(yearFirst, "Sept., Oct., Nov., Dec., Jan.");
    printf("These months have 1-31 days: %s\n\n", yearFirst);

    strcpy(yearSecond, "Mar., Apr., May., Jun. Jul., Aug.");
    printf("These months have 1-30 days: %s\n\n", yearSecond);

    strcpy(month, "Feb.");
    printf("%s has 1-28 days\n", month);

    return 0;
}

Upvotes: 1

Views: 139

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 754520

Only GCC allows zero-length arrays as a non-standard extension (and some compilers being compatible with GCC allow them too).

You can't store anything in such an array, of course, so passing yearFirst as an argument to strcpy() — whether the first or second argument — leads to undefined behaviour. Anything can happen. A crash is likely; it might even appear to work. Don't do it. Make sure you allocate enough space to store whatever you plan to copy into the array. It is a prime requirement of C programming; it is why some people prefer other languages where they don't have to pay attention to this sort of detail. But the C compiler isn't required to diagnose your dereliction of duty.

Upvotes: 2

Related Questions