Array of pointers [SOLVED]

Whether you're a newbie or an experienced programmer, any questions, help, or just talk of any language will be welcomed here.

Moderator: Coders of Rage

Post Reply
User avatar
Bullet Pulse
Chaos Rift Cool Newbie
Chaos Rift Cool Newbie
Posts: 89
Joined: Sun Feb 21, 2010 6:25 pm

Array of pointers [SOLVED]

Post by Bullet Pulse »

This seems like a pretty basic thing to me, but I can't figure it out for the life of me :roll:

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?
Last edited by Bullet Pulse on Mon May 24, 2010 6:57 pm, edited 1 time in total.
Image
User avatar
Ginto8
ES Beta Backer
ES Beta Backer
Posts: 1064
Joined: Tue Jan 06, 2009 4:12 pm
Programming Language of Choice: C/C++, Java

Re: Array of pointers

Post 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.
Quit procrastinating and make something awesome.
Ducky wrote:Give a man some wood, he'll be warm for the night. Put him on fire and he'll be warm for the rest of his life.
Live-Dimension
Chaos Rift Junior
Chaos Rift Junior
Posts: 345
Joined: Tue Jan 12, 2010 7:23 pm
Favorite Gaming Platforms: PC - Windows 7
Programming Language of Choice: c++;haxe
Contact:

Re: Array of pointers

Post 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++)
Image
User avatar
Bullet Pulse
Chaos Rift Cool Newbie
Chaos Rift Cool Newbie
Posts: 89
Joined: Sun Feb 21, 2010 6:25 pm

Re: Array of pointers

Post 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 :oops: .
Image
Live-Dimension
Chaos Rift Junior
Chaos Rift Junior
Posts: 345
Joined: Tue Jan 12, 2010 7:23 pm
Favorite Gaming Platforms: PC - Windows 7
Programming Language of Choice: c++;haxe
Contact:

Re: Array of pointers [SOLVED]

Post by Live-Dimension »

Eh, it's understandable in some cases, especially if you use languages that start as 1 instead of zero >_>.
Image
Post Reply