Skip to main content
gamedev.net
🔒 Locked

Problem with pointers

Started by saravananps Aug 24, 2006 at 5:35 AM 8 replies 1k views
Original Post
saravananps
saravananps
USHORT *pIndex = NULL; int Counter = 0; for (int j=0; j<2; j++) { *(pIndex++) = Counter; *(pIndex++) = Counter + j + 1; *(pIndex++) = Counter + j + 2; } i want *pIndex value to 0, 1, 2 in the first iteration. but when i'm checking the value for *(pIndex) it is zero for all. could any one help me
Nice Coder
Nice Coder
You are yet to allocate Pindex.

Use new :)
Click here to patch the mozilla IDN exploit, or click Here then type in Network.enableidn and set its value to false. Restart the browser for the patches to work.
saravananps
saravananps
i want the result 0, 1, 2, 0, 2, 3
Nitage
Nitage
You haven't allocated any memory for pIndex to point to, as a consequence the results of running your code are undefined - most probably just resulting in a crash due to an access violation.
saravananps
saravananps
i've allocated the memory to pIndex
pIndices = new USHORT [6];
but it still shows the same result
Rainault
Rainault
First, make sure that you allocated "pIndex", not "pIndices". Not sure if that's a typo or a real error in your code. Second, note that when you do *(pIndex++) for the first time, you're skipping the first element of the array. You increment the pointer to point to the second element, and that element receives the first 0. This is the sequence of events from the way I see it:

Before first iteration:
pIndex : ? ? ? ? ? ?

After first iteration:
pIndex : ? 0 1 2 ? ?

After second iteration:
pIndex : ? 0 1 2 0 2 (gah! seg fault?)

Why aren't you using the [] operator to access the elements of the array?

USHORT pIndex[6]; // Or, optionally, USHORT * pIndex = new USHORT[6];int Counter = 0;for (int j = 0; j < 2; ++j){   pIndex[3 * j] = Counter;   pIndex[3 * j + 1] = Counter + j + 1;   pIndex[3 * j + 2] = Counter + j + 2;}


And if you really want to use pointers...

USHORT * pIndex = new USHORT[6];int Counter = 0;--pIndex;for (int j = 0; j < 2; ++j){   *(++pIndex) = Counter;   *(++pIndex) = Counter + j + 1;   *(++pIndex) = Counter + j + 2;}


Note that my choice to use the pre-fix increment operator instead of postfix is merely a personal choice. It makes no real difference; you could have used *(pIndex++) just as well, like in your original code.
Nitage
Nitage
pIndices = new USHORT [6];for(int j=0; j<2; ++j){  *(pIndices++) = 0;  *(pIndices++) = j+1;  *(pIndices++) = j+2;}for(int index = 0; index < 6; ++index){    std::cout << pIndices[index];}delete[] pIndices;

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.