character array question.

I have a program that uses character arrays, and it works fine, but i am concerned about a possible problem.. not sure what its called, but the C++ book im reading just calls it "accessing too far into an array".
anyway..

1
2
3
char a[0];
cin >> a[0];
cout << a[0];


if the user put multiple charactors for the input of a[0] instead of just one character, would that result in "accessing too far into an array"?
i know that only the first character typed would be assigned to a[0], but what happens to the rest of the characters? just want to make sure a user cant accidentally mess up memory by putting more than one character..
No, that wouldn't. "accessing too far in an array" can cause a segmentation fault. This is when your program tries to access memory it doesn't own. The most common cause for this are dereferencing invalid pointers and accessing arrays out of bounds.
i.e.
1
2
3
4
5
6
7
8
9
10
//pointers
int* p = NULL;
int a = *p; //p is equal to NULL, and isn't a valid location

//arrays
int array[3] = {1,2,3};
array[3] = 4; //not good, the biggest indice here is 2, not 3
//accessing arrays out of bounds won't always segfault, but
//it will give you garbage values and can cause numerous
//other problems 


EDIT: I was playing around with chars. If the user enters multiple characters, only the first character gets stored in the variable. The rest are chopped off. This is done by the cin object I believe. If you hardcode a value of multiple chars, you get a compiler warning and only the last char is stored in the variable.
Last edited on
hmm.. well explain this to me please

1
2
3
4
5
6
7
8
    char a[0];
    char b[0];
    char c[0];
    cin >> b[0];
    cout << a[0] << endl;
    cout << b[0] << endl;
    cout << c[0] << endl;
    system("pause");


atleast on my computer, when a user puts in the character 'a' for b[0], 'a' gets assigned to all the other character arrays as well, same goes for any other character or number... whats going on?
I believe the problem lies with your declarations. When you put char a[0]; You are essentially saying "create a list of 0 chars". Try putting 1's instead of 0's inside the declarations. They would still be accessed with a 0, however, because array indices start at 0.

EDIT: Also, because the other arrays aren't initialized, you should get some garbage value. Perhaps 'a' was the garbage value in this case. (actual chance of that 1:10000000000)
Last edited on
If you create an array of size 1, why not just use a non array variable?
haha yeah.. i know this now =P i'm just not used to using charactors in the first place. now i feel stupid >_>
still an interesting concept though
Topic archived. No new replies allowed.