A few things.
-
When I declare my struct with a member array of size
3, wouldn’t that mean that array has 4 elements? 0, 1, 2, 3? Why them, when I try to insert the charactersA,B, andC, it tells meinitializer-string for array of chars is too long [-fpermissive]?#include <iostream> using namespace std; struct Student { double no; char grade[3]; }; int main() { struct Student harry = {975, "ABC"}; } -
When I print the address of a specific index of a character array I get the following results from the following code:
struct Student { double no; char grade[4]; }; int main() { struct Student harry = {975, "ABC"}; for (int i = 0; i < 4; i++) cout << "h.g[" << i << "]" << harry.grade[i] << endl; for (int i = 0; i < 4; i++) cout << "h.g[" << i << "]" << &harry.grade[i] << endl; }
Results:
h.g[0]A
h.g[1]B
h.g[2]C
h.g[3]
&h.g[0]ABC
&h.g[1]BC
&h.g[2]C
&h.g[3]
Why does the first index print ABC, and then BC, and so forth instead of each character separately like the first loop?
No, declaring an array like
T arr[3]gives you an array with 3 elements, not 4. The 3 in the declaration is the size of the array. Indices start at 0, so the indices for the elements are 0, 1, and 2.The string literal
"ABC"gives you an “array of 4const char” where the last element is the null character. Your program is ill-formed if you attempt to initialise an array with a string literal that has too many characters:In the first loop you are getting each character of the array and printing it out. When you print a
charyou get only thatcharas output.When you take the address of an element of the array, with
&harry.grade[i], you get achar*. When you output achar*, the I/O library treats it as a C-style null-terminated string. It will output from that character to the first null character it finds. That’s why you get the character at positioniand the characters following it.