1
#include <stdio.h>

int main(){

char array[2];
array[0] = 'q';
array[1] = 'a';
printf("%s",array);

return 0;
}

if you ask me this code should not work. printf prints array[2] like string but it's not a string. When i execute it, it works perfectly. Can you explain why?

LearningMath
  • 851
  • 4
  • 15
  • 38
  • Hmm... How do you think "string" are represented in C? – Alexei Levenkov Dec 16 '12 at 01:35
  • It doesn't work. Code "works" if it does what you expect. This code does not do what you expect. It has a bug and therefore doesn't work. Fix the bug and the mystery will go away. Yes, buggy code will do strange things that you don't expect and have trouble understanding. That's a good reason not to write buggy code. (Buggy code is *much* harder to understand than good code. Until you fairly thoroughly understand valid code, I wouldn't suggest even trying to understand buggy code.) – David Schwartz Dec 16 '12 at 01:36
  • 1
    You really shold invest in a beginner's book on C. Without understanding the fundamentals there's going to be a lot of things that don't make sense ... – Brian Roach Dec 16 '12 at 01:36

2 Answers2

5

When i execute it, it works perfectly.

You just got (un)lucky: your code exhibits undefined behavior, because it lets the printf's %s parameter run off the end of the sequence of characters that is not null-terminated.

A string in C is a sequence of char, which must have an extra character with the value 0, called the null terminator. Here is a way to make your code work without undefined behavior:

char array[3];
array[0] = 'q';
array[1] = 'a';
array[2] = '\0';
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
3

In C, String is identical to character arrays. There is no such thing as String in C.

luiges90
  • 4,493
  • 2
  • 28
  • 43
  • 4
    It might be worth noting that what he has is actually undefined behavior because there's no terminating `\0` – Brian Roach Dec 16 '12 at 01:35
  • when i say string i mean array of characters with terminating '\0'. this way printf doesn't know where to stop, so why it shows no errors? – LearningMath Dec 16 '12 at 01:38
  • @overflowed: Something had to occupy the byte after the end of the array, and it just happened to be a zero. Because the code is buggy, it depends on what happens to be in memory after the end of the array. – David Schwartz Dec 16 '12 at 01:51