0

I don't understand why this program print "klmnop" and not just "klm". b is an array of size 2! This is the code:

struct S
{
  int i1;
  int i2;
  char b[2];
};

int main()
{
  char a[] = "abcdefghijklmnop";

  struct S* s = a + 2;
  printf("[%s]\n" , s->b);

  return 0;
}
2
  • You realize that this code is UB in a system where sizeof(int) is 8 bytes? What are you trying to achieve? Commented Jul 2, 2012 at 10:15
  • It's a disaster from the standard-compliance point of view, with the implicit conversion from char * to struct S * with no real guarantee of alignment. But I think the point was clear enough. It could have just been printf("[%s]\n", a+10) though. It looks like a reduced form of a larger, non-hypothetical problem. Commented Jul 2, 2012 at 10:22

2 Answers 2

5

Like most string functions, your printf doesn't have any information about the size of the array that the string is contained in. It only has a pointer to a single char, and your promise that this char is the first in a sequence of chars terminated by '\0'. When asked to print the whole string, it'll keep going until it finds that terminator or crashes, whichever comes first.

Sign up to request clarification or add additional context in comments.

Comments

2

because printf("[%s]\n" , s->b); prints the data from the address s->b to the character '\0'. after the address s->b whenever it will find the '\0' it will print the data.

char b[2]; 

above statement do not include '\0' at the last character so it will continue reading the data from the address untill it find String terminator '\0'

1 Comment

I think you mean character \0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.