Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Strings

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
0
0
Can anyone please explain why when I declare:

struct EMPLOYEE
{
char lastname[30];
char firstname[30];
char middle[1];
int contact;
}

the character type variables can hold more than their declared subscript number and int type such as contact when given a value that start with zero is converted to a different number.

thanks in advance.
 
You can maybe write more data in your char arrays, but you are overwriting storage which does not belong to the program ,and most likely this will lead to severe errors at some point.

Code such as this

int i1 = 016;
cout << i1 << endl;

writes the value &quot;14&quot; to the console, since a leading zero indicates an octal number (i.e., the decimal value of the constant is 1*8+6 = 14, rather than 1*10+6 = 16 as for a decimal number). The following for example

int i1 = 018;

will cause a compile error, since &quot;8&quot; is not a valid octal digit. :) Hope that this helped! ;-)
 
...because in your structure declaration the string buffers are allocated in memory one after another, so character in lastname[30]is properly the character firstname[0]

but don't do that, it is dangerous and not legal to use such way of programming in c and will bring you multiple problems, but the way, assigning middle[1] will cause you GPF...
 
Because there is no run-time array bound checking in C/C++. It is the responsibility of the programmer to ensure that the code does not access outside the bound of the array.

Secondly, in a struct, memory are assigned as the same order as the declaration. If you write outside the boundary, you are effectively writing into the memory that is assigned for other struct member. If you writing outside the sturct, you might be writing into program memory and crash is almost assured.

HTH
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top