Originally Posted by
Terrance
Code:
#include <stdio.h>
main()
{
int i;
int i2;
int x[100][100];
int rowsUp;
int rowsAcross;
...
printf("You moved %i ", x[1][i2-2]);
printf("rows across.\n");
}
}
As Elysia pointed out, you have an error in this code related to array indexing. It may be illustrative to see a simple way to rewrite this program (without fixing the error) in C++ without using any other features except std::vector, which performs bounds checking. Notice that you can use the output of running this C++ program to improve (fix) your original C program. I also adjusted the output format to not scroll so much and included a simple automated testing function. This version is still incorrect, but the behaviour should at least be well-defined -- accessing an invalid index with .at(...) should cause the program to terminate.
Code:
#include <cstdio>
#include <cstdlib>
#include <vector>
using namespace std;
// Simulate user input for testing purposes.
int user_input(char endchar = '\n');
int main()
{
int i;
int i2;
// 100-by-100 int's, each initialized to 0.
vector<vector<int>> x(100, vector<int>(100, 0));
int rowsUp;
int rowsAcross;
for(;;) {
printf("Rows move up? (0-100 or -1 to quit): ");
rowsUp = user_input(); // scanf("%i\n", &rowsUp);
if (rowsUp == -1) {
printf("Bye.\n");
break;
}
printf("Rows to move across? (0-100): ");
rowsAcross = user_input(); // scanf("%i\n", &rowsAcross);
if(rowsUp >= 0 && rowsUp <= 100)
{
printf("up { ");
for(i = 0; i <= rowsUp; i++)
{
x.at(i-1).at(1) = i;
printf("%i ",x.at(i-1).at(1));
}
printf("}\n");
printf("You moved %i ", x.at(i-2).at(1));
printf("rows up.\n");
}
if(rowsAcross >= 0 && rowsAcross <= 100)
{
printf("across { ");
for(i2 = 0; i2 <= rowsAcross; i2++)
{
x.at(1).at(i2-1) = i2;
printf("%i ",x.at(1).at(i2-1));
}
printf("}\n");
printf("You moved %i ", x.at(1).at(i2-2));
printf("rows across.\n");
}
}
exit(0);
}
int user_input(char endchar /*= '\n'*/)
{
static vector<int> test_input = {
0, 0, // 0 rows up, 0 rows across.
1, 1, // 1 row up, 1 row across.
2, 2,
19, 45,
100, 100, // Maximum valid values.
101, 100,
101, 101,
-1, // Quit.
};
static size_t next=0;
if (next == test_input.size()) {
printf("%s: No more test input! Program will abort.\n", "user_input");
exit(1);
}
int v=test_input.at(next++);
printf("%d", v);
if (endchar != '\0') printf("%c", endchar);
return v;
}