A point could point to anything (reference anything), that could be a pointer to an object of a class , a pointer to a structure, a point to int, to char … to anything actually. A managed environment means that your J VM or .net CLR, takes care of a lot of things for you…
Anyway, in c and c++ you can use a pointer to point to anything simply as follows:
int* p ; char* p;
this is the declaration, it doesn’t point to anything now… in other languages, if you tried to use this pointer it will throw an exception , in c it wont it will simply get you the value that originally existed in the place you are pointing to… and if you attempted to write to it, you will overwrite someone else’s data or in best cases you will write in a random place where no one knows if it is used or not. You can get the address of any variable in c using the & operator:
int x = 0; int* p = &x;
that way, p is pointer that points to x. to get the value in x we use the * operator:
*p = 6;
You could a pointer value to another with no problems:
nt* p2 = p;
an important usage of the pointer is passing a variable by reference if we have a function as follows:
void SomeFunctionName (int s)
{
S = 5;
}
And used as follows:
int x = 2; SomeFunctionName(x);
Written like this:
void SomeFunctionName (int* s)
{
*S = 5;
}
And used as follow:
int x = 2; SomeFunctionName (&x);
In c an array is a pointer to the first element of the array. The point here is the dynamic allocation... Note: add the lib where the function malloc exist in malloc.h and in the code:
int* ar = (int*)malloc (10 * sizeof(int));
note: that in c you can say the following:
ar++;
What if I want to pass an array to a function I would do the following:
void foo (int* par)
{
par[3] = 3;
}
And pass it using the following:
foo(ar);
If I tried to do that the way in the previous example, like the following:
void foo(int* par)
{
par = (int*)malloc (10 * sizeof(int));
}
And pass it using the following:
foo(ar);
Nothing will happen, we have changed what the pointer “par” points to not what the original array points to…
For this to work, we need to make a pointer to pointer… That is written like this:
int** pp = &ar;
here we are assigning the address of the ar pointer to pp… that way we can do the following:
*pp = (int*)malloc (10 * sizeof(int));
That will change the value of ar… Thus we could do the following to the function:
void foo(int** par)
{
*par = (int*)malloc (10 * sizeof(int));
}
And pass it using the following:
foo(&ar);
That’s all… my goal was to overview the pointers briefly… you will have some long book in the c to get it all but this is the short version… Thank you.
Comments
Hi, Great work, I
Hi,
Great work, I modified it a bit to improve the code formating :)
I had a question though, do we need all the inter-language talk? I find it a bit confusing and distracting.
What do you think ?
Pointers are _NOT_
Thanks for the feedback
Thanks for the feedback, I have made some enhancements with your comment.