0
char name[4][20];
int count=0;
cout<<"Enter 4 name at most , one name per line:\n";
while(cin.getline(name[count++],20))
 ;
--count;

(rest of code is for printing if u need to see that too it's at the end)

when i Enter names more than 4 it still prints those names but how can that happen? because the first dimension is 4 so how can it get more than four

printing part of code:

for(int i=0; i<count; i++)
{
        cout<<i<<"="<<name[i]<<endl;
}
system("pause");
}
user3783574
  • 127
  • 9
  • You need to tell it to stop after 4. The `while` command has no idea how big the array is. – Galik Sep 13 '14 at 07:58
  • but the first dimension is 4 so when it gets more than 4 the program should give an error or something the additinal names should go to NAME(the array) anyway but how that can happen when the first dimension is 4 – user3783574 Sep 13 '14 at 08:00
  • 1
    Accessing outside the bounds of the array is undefined behavior. It might crash, it might not, it might blow bubbles out of your speakers. It's up to you to stick to the bounds. – Retired Ninja Sep 13 '14 at 08:01
  • 1
    "but the dimension is 4" - I know that and you know that but the `while()` doesn't. All it cares about is what conditions you tell it to stop at. Currently it will only stop when `cin.getline()` fails. – Galik Sep 13 '14 at 08:02
  • 2
    possible duplicate of [C++ Accesses an Array out of bounds gives no error, why?](http://stackoverflow.com/questions/1239938/c-accesses-an-array-out-of-bounds-gives-no-error-why) – Retired Ninja Sep 13 '14 at 08:02

2 Answers2

1

You need to tell the while() loop when to stop.

Try this:

char name[4][20];
int count=0;
cout<<"Enter 4 name at most , one name per line:\n";
while(count < 4 && cin.getline(name[count++],20))
    ;
Galik
  • 47,303
  • 4
  • 80
  • 117
1

If I get it correctly, your are asking "why if the array is 4 I can fit 5?".
Unlike Pascal, where arrays boundaries are checked at runtime, C++ doens't do such thing.

Think about it. An array is just some pointer that is added the offset later.
Let's say that you've an array of 5 integers and you do this

int a[5];
a[3] = 3;
a[6] = 4;

Nothing is really wrong, because in the first assignment, the statement equals to a+12 and the second one a+24. You're just incrementing the pointer and unless you don't bother the OS, you could go on and potentially overwrite some other data.
So C++ will very unlikely say something if you cross the arrays boundaries. This implies that you must always somehow know how big is the array, in your case by simply adding to the loop:

while(count < 4 && cin.getline(name[count++], 20));
EnryFan
  • 422
  • 3
  • 15