user1479376
user1479376

Reputation: 337

array in c and struct

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;
}

Upvotes: 0

Views: 95

Answers (2)

Hemant Metalia
Hemant Metalia

Reputation: 30698

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'

Upvotes: 2

Alan Curry
Alan Curry

Reputation: 14741

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.

Upvotes: 5

Related Questions