-1

I am new to C and I'm getting confused about printing arrays.

Consider this simple code:

char myName [5] = "tamir";
printf("My name is %s" , myName);

The output of this is "tamirH", with extra H at the end.

But when I declare this array like this char myName [6] = "tamir"; (now the array is declared with 6 chars and "tamir" is made out of 5 chars) I don't see the extra "H".

Why is this happening? Is this related to the string terminator in C or am I confused?

Tamir Abutbul
  • 7,301
  • 7
  • 25
  • 53
  • 1
    "tamir" is a string of *6* characters long. Remember that strings re terminated with a special `'\0'` character. – Eugene Sh. Jun 19 '19 at 16:32
  • Related: [Why does gcc allow char array initialization with string literal larger than array](https://stackoverflow.com/questions/13490805/why-does-gcc-allow-char-array-initialization-with-string-literal-larger-than-arr) – Raymond Chen Jun 19 '19 at 16:35

1 Answers1

1
char myName [6] = "tamir";

will work. And to avoid human errors, it would be even better to simply declare char myName[] and let the compiler allocate memory for you. (comment suggested by @fassn ) The string literals are converted in a static char array adding also a NULL. You need to reserve space for NULL as well. "tamir" is syntactic sugar for {'t', 'a', 'm', 'i', 'r', 0}. The very definition from ISO/IEC 9899 is so, 6.4.5p5 String literal

In translation phase 7, a byte or code of value zero is appended to each multibytecharacter sequence that results from a string literal or literals.

alinsoar
  • 15,386
  • 4
  • 57
  • 74
  • 2
    And to avoid human errors, it would be even better to simply declare `char myName[]` and let the compiler allocate memory for you. – fassn Jun 19 '19 at 16:38
  • 1
    @alinsoar What a funny mistake, I was sure that In C you can't declare an array as `myName[]` and let the compiler allocate memory for you as @fassn said. It really makes things clear now. I will accept your question when I will be able to (cant before 10 minutes). Have a great day – Tamir Abutbul Jun 19 '19 at 16:42