0

I know that in C string assignment must go through

char string[4];
strcpy(string, "aaa");

but why and how does C allow

char string[] = "string";

?

Thanks in advance

Daniel Jee
  • 664
  • 5
  • 10
  • 1
    C has never had( and never will?) a native a string type. A character sequence terminated by `\0` is a considered a string. – sjsam Jul 28 '16 at 09:20
  • 4
    http://stackoverflow.com/questions/1704407/what-is-the-difference-between-char-s-and-char-s-in-c – P.P Jul 28 '16 at 09:21
  • 1
    @P.P. Not exactly the same - this is the difference between `char string[4]` and `char string[]` while the other is between `char string[]` and `char *string`. – skyking Jul 28 '16 at 09:25
  • Probably this link could help you http://stackoverflow.com/questions/579734/assigning-strings-to-arrays-of-characters – Karthick Jul 28 '16 at 10:02

2 Answers2

2

You seem to have misunderstood something. According to gcc you are allowed to do:

char string[4] = "aaa";

The difference to char string[] = "aaa"; is only that the compiler infers the length of string from it's initializer. There's nothing different to other types of arrays here - just the fact that you may use a string literal as an initializer instead of an array literal.

skyking
  • 13,817
  • 1
  • 35
  • 57
  • I assigned a string to a character array char string[] = "aaa" but I could change the content afterwards. No errors. – Daniel Jee Jul 28 '16 at 09:32
  • @FabioTurati I removed that paragraph so your comment about my last paragraph only applies to a paragraph that is no longer present... – skyking Jul 31 '16 at 10:19
2
char string[] = "string";

Here, the right length of string is automatically calculated by the compiler so that there's enough room for the string and the NUL character.

char string[4];
strcpy(string, "aaa");

Here strcpy may access beyond the array bounds if the string is larger than the actual string capacity.

edmz
  • 8,220
  • 2
  • 26
  • 45
  • If strcpy can access beyond the array bounds does that mean it assigns memory address for the array depending on the size of the string? – Daniel Jee Jul 28 '16 at 09:36
  • 1
    No, it just keeps on writing in the following memory addresses, occupied by other variables, producing undefined results. This technique is used for buffer overflow attacks, so if you are doing strcpy from strings given by user, you must check first that the size of the destination buffer is big enough. – AwkMan Jul 28 '16 at 09:45
  • @hemel: No, it does not resize the array (what you say): that's _your_ job. It's just writes past the bounds of the array, leading to UB. – edmz Jul 28 '16 at 12:37
  • So if there was a preoccupied memory address following the one occupied by the array and the string is quite long, could it corrupt the data in the preoccupied memory address? – Daniel Jee Jul 29 '16 at 02:59