user3783574
user3783574

Reputation: 127

array getting more than it should

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");
}

Upvotes: 0

Views: 65

Answers (2)

EnryFan
EnryFan

Reputation: 422

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));

Upvotes: 1

Galik
Galik

Reputation: 48645

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))
    ;

Upvotes: 1

Related Questions