Adding a value at the end of the array

Apr 7, 2016 at 9:53pm
asdxxxd
Last edited on Apr 8, 2016 at 2:59am
Apr 7, 2016 at 10:24pm
It seems to me some better names would help out. For instance, the function name add could be misleading - If I'm understanding the prompt of your exercise correctly, you're effectively "appending" values to an array.

I've rewritten your code to reflect some better name choices, and what I think you should be actually doing:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
struct ArrayList {
	const static int num_data = 100;
	int data[num_data];
	int current;
};

bool append(ArrayList& list, int value) {

	if (list.current >= list.num_data) {
		return false;
	}

	list.data[list.current] = value;
	list.current++;

	return true;

}


Here are the problems with the code snippet you provided:

1
2
3
for (int i = 0; i<al.count; i++) {
			i = index;
		}


At this point in the code, index hasn't been initialized. It contains garbage. You then assign garbage to i, which is responsible for iterating through the array (it doesn't even do that, though). This is like asking someone to count to 100, and then immediately shooting them in the face. The way you have it, you cannot possibly know when the loop will end - and the whole loop is pointless to begin with since it's not actually doing anything to the array.

al.data[index] = value;

Once that loop ends (if it does), you're accessing an out-of-bounds element in the array with index, which still contains garbage. This is dangerous.
Last edited on Apr 7, 2016 at 10:32pm
Topic archived. No new replies allowed.