-1

I have declared two simple character arrays. When calling printf() on one string both arrays are printed. Why?

#include <stdio.h>

int main()
{
    char z[] = "The C programming language.";

    char v[2] = {'q', 'w'};

    printf("%s \n", v); 

    return 0;
}

Result expected: qw. Result obtained: qwThe C programming language. The two arrays are joined??

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
george
  • 15
  • 3
  • 11
    `char v[2] = {'q', 'w'};` this is not a null-terminated string. Printing that with `%s` is undefined behavior. Try making it `char v[3] = {'q', 'w', '\0'};` instead. If you're not sure how to make and handle strings, I recommend picking up [a good book](https://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list) that helps you learn the language. – Blaze Jul 05 '19 at 07:23
  • 2
    Welcome to the magic world of the Undefined Behaviour. It printed it because by accident the thirs char was zero. But it can be anything as you do not control it. But anything else may happen including ordering the pizza, sending your personal data to the fraudsters – 0___________ Jul 05 '19 at 07:24
  • The difficulty with undefined behavior is that you often get no warning at compiler-time and erratic behavior at run-time. This online C interpreter will tell you that the `printf` call invokes undefined behavior: https://taas.trust-in-soft.com/tsnippet/t/29b455f2 – Pascal Cuoq Jul 05 '19 at 08:34

2 Answers2

1
  1. 'q' is not the array only the integer.
  2. When you initialize the array those two integers are stored as array elements.

  3. Nothing is joined.

  4. It is undefined behaviour as printf looks for the terminating zero and reads outside array bounds

0___________
  • 60,014
  • 4
  • 34
  • 74
0

In your example, z is a string, but v is a byte array.

The difference? z terminates with a \0 character, v does not.

Therefore it is OK to use printf() with %s to print a string, but you MUST use a for() (or something else similar) to print an array.

virolino
  • 2,073
  • 5
  • 21