-1

I' studying for my test and I came across with a decent code with weird results. I understand the result of the first two lines in main(), however I don't understand why my computer prints the answer like the picture!!

What is s[%d] doing there??? result of the code

#include <stdio.h>

void printstring(char s[]) {
    int i;

    for (i = 0; i < 10; i++)
        printf(" s[%d]", i);
    printf("\n");

    for (i = 0; i < 10; i++)
        printf("%5c", s[i]);
    printf("\n");

    for (i = 0; i < 10; i++)
        printf("%5X", s[i]);
    printf("\n");
    printf("\n");
}

main() {
    printstring("I am beautiful");
    printstring("beautiful");
    printstring("");
}
klutt
  • 30,332
  • 17
  • 55
  • 95
SoSueat
  • 63
  • 5
  • 4
    You are invoking *undefined behavior* by accessing past the actual length of the string – UnholySheep Oct 17 '17 at 12:43
  • I'm totally new to C so I'm not sure why it's an undefined behavior. – SoSueat Oct 17 '17 at 12:44
  • 2
    How many characters is there in `"beautiful"`? How many in `""`? What do you think happens when you go out of bounds of an array (and string literals *are* arrays)? – Some programmer dude Oct 17 '17 at 12:44
  • Well 9 characters in "beautiful" and none in "". I expected all zeros. So do you mean what I wrote doesn't make sense at all?? – SoSueat Oct 17 '17 at 12:46
  • Please don't post images unless necessary. The output is text so you should post it as text. – klutt Oct 17 '17 at 12:46
  • 1
    [What are all the common undefined behaviours that a C++ programmer should know about?](https://stackoverflow.com/questions/367633/what-are-all-the-common-undefined-behaviours-that-a-c-programmer-should-know-a) It's C++, but many of them apply to C as well – 001 Oct 17 '17 at 12:47
  • Roughly spoken: the values you beyond the bounds of an array are at best undetermined, at worst your program could crash when you try to read/write them – Jabberwocky Oct 17 '17 at 12:48
  • I'd say it would be *best* if the program just crashed. – Antti Haapala -- Слава Україні Oct 17 '17 at 12:49
  • Please see [How dangerous is it to access an array out of bounds?](https://stackoverflow.com/questions/15646973/how-dangerous-is-it-to-access-an-array-out-of-bounds). Strange output is just about the nicest result you can get... – Bo Persson Oct 17 '17 at 12:51
  • `""` is an array of one char (`char [1]`), that must not be modified. You're accessing (reading from it) out of bounds. – Antti Haapala -- Слава Україні Oct 17 '17 at 12:53

1 Answers1

1

because arrays in c/c++ has no explicit boundary,in the third call of printstring, the array s is a zero-length char array. when dereference value use subscript 0..10, it refers to a random storage in memory which its value depends on the compiler and the structure of object file it generated. and in your case, the string "s[%d]" are just in the place 3 bytes after s refers.

kiwi95
  • 26
  • 4