-
pointers and memory
howdy,
im learning pointer and memory management from a book. ive been playing with this C++ stuff for a few months now but when i start reading and typing the sample code for the pointers i can not get a handle on what is going on. for example:
~~~~~~~~~~~code~~~~~~~~~~~~~~~
#include <iostream.h>
#include <iomanip.h>
int main()
{
int stuff[3][4] = {{11, 22, 45, 23},
{33, 67, 28, 45},
{98, 4, 71, 90}};
int *ip;
int(*ip4)[4]; //WHAT IS THIS FOR?
int i, j;
ip4 = stuff;
ip =(int *) stuff; //POINTER NOT TO AN ARRAY??
cout<<"Storage of date: "<<endl'
for(i=0;i<4; i++)
cout<<ip[i];
cout<<endl;
cout<"Matrix concept: "<<endl;
for(i=0; i<3; i++)
{
for(j=0; j<4; j++)
{
cout<<*(*(ip4 =i) + j)<<" "; //WHAT IS THIS DOING
}
cout<<endl;
}
getchar(); //freezes the screen
return 0;
}
~~~~~~~~~~~~~code~~~~~~~~~~~~~~~~~
:mad: sorry about the format i couldnt figure out how to put @#&%$ code tags on this thing.
thanks
M.R.
-
int(*ip4)[4]; //WHAT IS THIS FOR?
That statement is declaring a variable called ip4, which is a pointer to an array of 4 integers.
ip =(int *) stuff; //POINTER NOT TO AN ARRAY??
ip is a pointer to an integer. stuff is a 2 dimensional array containing 3 x 4 integers. when you refer to 'stuff' in your code' you are doing the same as saying '&stuff[0][0]' ... and since this is an address containing and integer value, you are able to point an integer pointer to it.
cout<<*(*(ip4 =i) + j)<<" "; //WHAT IS THIS DOING
hrm.. interesting statement... are you sure you didn't type it wrong?? It should be ip4 + i shouldn't it?? It's using i to offset the address of the pointer (ie... to reference array 1, 2 and 3 in the 2d stuff array), and using j to loop through the items in that array. it's just using pointers and dereferencing rather than array indexes...
getchar(); //freezes the screen
this doesn't freeze the screen... it waits for user input (one character).... used a lot for the 'press a key to continue' type functionality.
hope this helps.
U.
-
Heh, I was wondering about that = in there...
-
Code:
#include <stdio.h>
#include <iostream.h>
#include <iomanip.h>
int main()
{
int stuff[3][4] = { {11, 22, 45, 23},
{33, 67, 28, 45},
{98, 4, 71, 90} };
int *ip;
int(*ip4)[4]; //WHAT IS THIS FOR?
int i, j;
ip4 = stuff;
ip =(int *) stuff; //POINTER NOT TO AN ARRAY??
cout<<"Storage of date: " << endl;
for(i=0;i<4; i++)
cout << ip[i];
cout << endl;
cout << "Matrix concept: " << endl;
for(i=0; i<3; i++) {
for(j=0; j<4; j++) {
cout << *(*(ip4 +i) + j) << " "; //WHAT IS THIS DOING
}
cout << endl;
}
getchar(); //freezes the screen
return 0;
}
a bit more legible.
-
sorry folks,
the = is a suposed to be a +. I have to add that getchar(); so when i move this code from linux back to borland it wont disapear before it confuses the he__ out of me;).
thanks for the explaination. ill digest this thing and keep forging ahead.
Thanks
M.R.