strange error



struct net{
char PIPIN[2];
char POPIN[2];
}n[11];

//change PIPIN and POPIN value here.

cout<<n[0].PIPIN<<", "<<sizeof(n[0].PIPIN);

// The result is: 2424,2
//here I do not know why the PIPIN size is 2, but the value printed is 2424
n[0].PIPIN is a char array. When you cout a char array it's like printing a string.

For example:

1
2
3
char foo[] = "A string";  // foo is a char array

cout >> foo;  // this prints "A string" 


You happen to be getting "2424" because you never set PIPIN to anything, so that just happens to be what the array(s) contain. (or perhaps you set PIPIN[0] to '2' and PIPIN[1] to '4'?)

Note that this is bad because your string is not null terminated and therefore it's spilling out past the end of the buffer -- which could potentially crash your program.


sizeof(n[0].PIPIN), as the name suggests, gives you the size of PIPIN. Since PIPIN is an array of 2 characters, and each character is a byte.... 2 characters * 1 byte each = total size of 2 bytes.
Last edited on
Topic archived. No new replies allowed.