To start off, here's my code:
Okay so it compiles fine, but running gives me
// setting stuff up
int int_size = sizeof(int);
int commands = 5;
int max_bytes = 3;
int byte_array = (int)malloc(int_size*commands*max_bytes);
int* pbyte_array = &byte_array;
cout << (0x0012FF3C+(int_size*1)) << "\n\n";
cout << pbyte_array << "\t+\t";
cout << i*int_size << "\t=\t";
cout << pbyte_array+(i*int_size) << "\n";
Basically it's adding 16 each time. If I change it to
0012FF3C + 0 = 0012FF3C
0012FF3C + 4 = 0012FF4C
0012FF3C + 8 = 0012FF5C
0012FF3C + c = 0012FF6C
0012FF3c + 38 = 0013001C
it adds 4 to the output (instead of 1 as it should). I notice if I change pbyte_array declaration to
cout << pbyte_array+1
then it works fine (although the hex output becomes lowercase o_O). I have checked the output of int_size and it's 4 as it should be. If I type the address directly into the loop it does the same thing as it does with the changed pbyte_array declaration.
int pbyte_array = (int)(&byte_array)
Basically I want a a pointer/address and the addition of an offset.
I'm running Visual C++ 2008
Oh and also I couldn't get arrays to work properly oddly, which is why I created this code in the first place. It kept saying it couldn't convert (int*) to (int).
sizeof(int) = 4. Since you have your array declared as type int, adding one to the pointer will take you to the next int, four bytes away. Since you add (i*int_size), you're adding 4, which means that you go four ints down the line, sixteen bytes away.
PS: int* and int aren't the same thing. What were you trying to do.
So use a type which has a size of 1 (say unsigned char), not 4 (as is the case with your ints).
Thanks, I got it working.. just changed it to
cout << pbyte_array+i << "\n";
I know they aren't the same.. which is why it confused me, I was just going
my compiler errors are
testarray = new int;
changing it to
'testarray': unknown size.
'=': cannot convert from 'int *' to 'int '
didn't help either.. more errors
Obvious way to do that:
Way to do that for people who insist on new:
You can't declare an array without giving it a size.
testarray = new int;
Okay thanks... I did get a warning with
though. Thanks anyway though!
You obviously don't know what pointers are and what the heap is or how to allocate memory.
When allocating on the heap, we keep track of the memory by the use of pointers.
Anyway, I suggest you stay away from pointer + n, because it's confusing and is obviously confusing you too. Use pointer[n] instead.
Originally Posted by RobotGymnast