Page 1 of 1
Array of pointers [SOLVED]
Posted: Mon May 24, 2010 6:21 pm
by Bullet Pulse
This seems like a pretty basic thing to me, but I can't figure it out for the life of me
Code: Select all
int* testArray[10];
for (int i = 1; i <= 10; i++)
{
testArray[i] = new int();
*testArray[i] = i; //Why does this work if the below doesn't?
}
*testArray[0] = 5; //Produces an error
cout << *testArray[0]; //Prodcues an error
Unhandled exception at 0x0117109f in MemoryTester.exe: 0xC0000005: Access violation reading location 0xcccccccc.
How come?
Re: Array of pointers
Posted: Mon May 24, 2010 6:43 pm
by Ginto8
2 things. First: it should be i < 10 not i <= 10. Array indexing of an array of n values is accessed with [0] to [n-1]. Secondly, i should start at 1, because otherwise [0] does not get allocated.
Re: Array of pointers
Posted: Mon May 24, 2010 6:52 pm
by Live-Dimension
Don't you mean i should start at 0?
What your doing wrong is simple. You have your array as 10 elements, but your putting new ints at [1] instead of [0]. So the for loop works perfectly, but when you try to access [0] it throws an error.
Use this instead.
for (int i = 0; i < 10; i++)
Re: Array of pointers
Posted: Mon May 24, 2010 6:57 pm
by Bullet Pulse
Live-Dimension wrote:Don't you mean i should start at 0?
What your doing wrong is simple. You have your array as 10 elements, but your putting new ints at [1] instead of [0]. So the for loop works perfectly, but when you try to access [0] it throws an error.
Use this instead.
for (int i = 0; i < 10; i++)
*facepalm*. I can't believe I did this lol

.
Re: Array of pointers [SOLVED]
Posted: Tue May 25, 2010 1:05 am
by Live-Dimension
Eh, it's understandable in some cases, especially if you use languages that start as 1 instead of zero >_>.