What is the significance of (int*) in this program? - c++

I wrote two programs which prints out the variable the pointer p points to:
First program:
#include <stdio.h>
int main (void){
int *p;
int a=5, q;
p=&a;
q=*p;
printf("%d", q);
}
Second program:
#include <stdio.h>
int main(void)
{
int a=5;
int*p;
p= (int*)&a;
printf("%d", *p);
return 0;
}
My question:
Both the programs print the value of a which is 5. However, the second program uses p=(int*)&a; instead of just p=&a;. Could someone please tell me the significance of (int*) casting here?

Casting is a way for a programmer to tell the computer that, even though the computer thinks something is one type, we want to treat it as another type.
But here the cast is of no use as here a is an integer and thus address of a will need no cast here for integer pointer.

There is no significance, rather, this cast is superfluous and not required.
In your code, a is of type int, p is of type int *. Hence,
p= (int*)&a;
and
p= &a;
are same and the second one here is recommended.

It's useless.
a is an int, so &a is already a pointer to int.

Useless use of type casting. It's like,
int a = (int) 10 ;

That is typecasting ,to tell the compiler that the value that is assigned to the pointer p that is &a is an integer type(int) but there it is of no use as &a return the address that is assigned to the variable a and it is always an integer.

Related

What is the difference between int* p and int** p in c++? [duplicate]

What is the difference between int* i and int** i?
Pointer to an integer value
int* i
Pointer to a pointer to an integer value
int** i
(Ie, in the second case you will require two dereferrences to access the integer's value)
int* i : i is a pointer to a object of type int
int** i : i is a pointer to a pointer to a object of type int
int*** i : i is a pointer to a pointer to a pointer to object of type int
int**** i : i is a pointer to a pointer to a pointer to a pointer to object of type int
...
int* pi
pi is a pointer to an integer
int **ppi
ppi is a pointer to a pointer to an integer.
EDIT :
You need to read a good book on pointers. I recommend Pointers on C by Kenneth Reek.
Let's say you're a teacher and have to give notes to one of your students.
int note;
Well ... I meant the whole class
int *class_note; /* class_note[0]: note for Adam; class_note[1]: note for Brian; ... */
Well ... don't forget you have several classes
int **classes_notes; /* classes_notes[0][2]: note for Charles in class 0; ... */
And, you also teach at several institutions
int ***intitute_note; /* institute_note[1][1][1]: note for David in class 1 of institute 1 */
etc, etc ...
I don't think this is specific to opencv.
int *i is declaring a pointer to an int. So i stores a memory address, and C is expecting the contents of that memory address to contain an int.
int **i is declaring a pointer to... a pointer. To an int. So i contains an address, and at that memory address, C is expecting to see another pointer. That second memory address, then, is expected to hold an int.
Do note that, while you are declaring a pointer to an int, the actual int is not allocated. So it is valid to say int *i = 23, which is saying "I have a variable and I want it to point to memory address 23 which will contain an int." But if you tried to actually read or write to memory address 23, you would probably segfault, since your program doesn't "own" that chunk of RAM. *i = 100 would segfault. (The solution is to use malloc(). Or you can make it point to an existing variable, as in int j = 5; int *i = &j)
Imagine you have a few friends, one of them has to give you something (a treasure... :-)
Say john has the treasure
int treasure = 10000; // in USD, EUR or even better, in SO rep points
If you ask directly john
int john = treasure;
int you = john;
If you cannot join john, but gill knows how to contact him,
int john = treasure;
int *gill = &john;
int you = *gill;
If you cannot even join gill, but have to contact first jake who can contact gill
int john = treasure;
int *gill = &john;
int **jake = &gill;
int you = **jake;
Etc... Pointers are only indirections.
That was my last story for today before going to bed :-)
I deeply believe that a picture is worth a thousand words. Take the following example
// Finds the first integer "I" in the sequence of N integers pointed to by "A" .
// If an integer is found, the pointer pointed to by P is set to point to
// that integer.
void f(int N, int *A, int I, int **P) {
for(int i = 0; i < N; i++)
if(A[i] == I) {
// Set the pointer pointed to by P to point to the ith integer.
*P = &A[i];
return;
}
}
So in the above, A points to the first integer in the sequence of N integers. And P points to a pointer that the caller will have the pointer to the found integer stored in.
int Is[] = { 1, 2, 3 };
int *P;
f(3, &Is[0], 2, &P);
assert(*P == 2);
&P is used to pass the address of P to the function. This address has type int **, because it's the address of a pointer to int.
int* i is the address of a memory location of an integer
int** is the address of a memory location of an address of a memory location of an integer
int* i; // i is a pointer to integer. It can hold the address of a integer variable.
int** i; // i is a pointer to pointer to integer. It can hold address of a integer pointer variable.
Neither is a declaration. Declaration syntax does not allow () around the entire declaration. What are these () doing there? If this is supposed to be a part of function declaration, include the whole function declaration thing in your question, since in general case the actual meaning of a declaration might depend on that. (Not in this one though.)
As for the difference... There is one * in the first and there are two *s in the second. Does it help? Probably not. The first one declares ias a pointer to int. The second one declares i as a pointer to int *. Does this help? Probably not much either. Without a more specific question, it is hard to provide a more meaningful answer.
Provide more context, please. Or, if this is actually as specific as it can get, read your favorite C or C++ book about pointers. Such broad generic questions is not something you ask on the net.
Note that
int *i
is not fully interchangeable with
int i[]
This can be seen in that the following will compile:
int *i = new int[5];
while this will not:
int i[] = new int[5];
For the second, you have to give it a constructor list:
int i[] = {5,2,1,6,3};
You also get some checking with the [] form:
int *i = new int[5];
int *j = &(i[1]);
delete j;
compiles warning free, while:
int i[] = {0,1,2,3,4};
int j[] = {i[1]};
delete j;
will give the warnings:
warning C4156: deletion of an array expression without using the array form of 'delete'; array form substituted
warning C4154: deletion of an array expression; conversion to pointer supplied
Both of these last two examples will crash the application, but the second version (using the [] declaration type) will give a warning that you're shooting yourself in the foot.
(Win32 console C++ project, Visual studio 2010)
Textual substitution is useful here, but beware of using it blindly as it can mislead you (as in the advanced example below).
T var; // var has type T
T* var; // var has type "pointer to T"
This works no matter what T is:
int* var; // pointer to int
char* var; // pointer to char
double* var; // pointer to double
// advanced (and not pure textual substitution):
typedef int int3[3]; // confusing: int3 has type "array (of size 3) of ints"
// also known as "int[3]"
int3* var; // pointer to "array (of size 3) of ints"
// aka "pointer to int[3]"
int (*var)[3]; // same as above, note how the array type from the typedef
// gets "unwrapped" around the declaration, using parens
// because [] has higher precedence than *
// ("int* var[3];" is an array (size 3) of pointers to int)
This works when T is itself a pointer type:
typedef int* T; // T is a synonym for "pointer to int"
T* var; // pointer to T
// which means pointer to pointer to int
// same as:
int** var;

C++ pointers: dereferencing, assigning values, etc

The questions I'm asking are very basic, but I'm trying to understand the behaviour of pointers in C++ by doing exercises in the compiler. So, for example, I start by declaring an int pointer *p and trying to ascribe it some values and print it:
#include <iostream>
using namespace std;
int *p, i;
int main(){
i=5;
p=&i;
cout<<*p<<endl;
return 0;
}
This is very clear and easy, right? But while I'm wondering why the C++ syntax works this way, I test another way of assigning a value to a pointer:
#include <iostream>
using namespace std;
int *p, i;
int main(){
i=5;
p=&i;
*p=3;
cout<<*p<<endl;
return 0;
}
Obviously, the result is different now. The question is, why this wouldn't work:
#include <iostream>
using namespace std;
int *p, i;
int main(){
*p=3;
i=5;
p=&i;
cout<<*p<<endl;
return 0;
}
Why do I have to dereference the pointer first before assigning it a value, but direct assignment would not work without dereferencing?
Also, if in the second example I wrote I added another assignment:
int main(){
i=5;
p=&i;
*p=3;
*p=6;
cout<<*p<<endl;
return 0;
}
This would not change the value stored at *p (it would still be 3). I don't simply want to learn by memorising this pointer behaviour, I'm interested in understanding why it works this way. Thanks.
#include <iostream>
using namespace std;
int *p, i;
int main(){
*p=3;
i=5;
p=&i;
cout<<*p<<endl;
return 0;
}
This doesn't work because you are trying to assign a value to the integer that p points to. That's what this line does:
*p = 3;
That means, "store the value 3 at the location which p points at". But p doesn't point at anything, because you didn't assign it to point to anything until two lines later.
p = &i;
That means, "assign the address of i to be the value of p". Or, in other words, "store the address of i in p". p needs to point to something, before you can assign to the thing p points to. Otherwise you have undefined behavior.
On the last section:
int main(){
i=5;
p=&i;
*p=3;
*p=6;
cout<<*p<<endl;
return 0;
}
You say this: "This would not change the value stored at *p (it would still be 3)." -- I'm not sure why you say that. Yes, it would change the value stored at *p (which is the value of i). It changes it to 6.
The question is, why this wouldn't work:
int *p, i;
int main(){
*p=3;
here you attempt to dereference p and write something, but since p is uninitialized here (it can be 0, for example), you are trying to write to memory that you didn't allocate, thus this is a segmentation fault.
Also, if in the second example I wrote I added another assignment: [...] This would not change the value stored at *p (it would still be 3).
Actually, it would. Why would you think otherwise?
I'm interested in understanding why it works this way.
You're on the right track, just continue reading (e.g. this thread) and experimenting!

difference between a pointer and a pointer array

I made a code
#include <iostream>
#include<conio.h>
using namespace std;
void main()
{
int *x,*y;
x=new int[1];
y=new int;
cin>>y; //Gives error probably because y is a pointer and not a variable
cin>>*y //works fine
cin>>x[0]>>x[1];
cout<<x[0]<<x[1];
cout<<*x[0]; //gives error
cout<<y;
cout<<*y;
getch();
}
gives error.why?I remember i declared x as a pointer array and now i m doing the same i did with *y.Does it mean that a pointer array becomes a variable?plz help!
What you are actually doing with that line of code is similar to:
cout<<**x;
Because using x[0] will dereference the 0th element of x.
As you can see by your definition of x, x is just a pointer, not a pointer to a pointer, so dereferencing it twice will not work since you are trying to dereference a variable.
What the line:
x=new int[1];
is actually doing is just saying "assign an array of ints, size 1 to this pointer", which will just make x point to a block of memory big enough to store 1 int.
x is a pointer to an int. You have allocated an array of ints, which is a single int long. Therefore x[0] is an int and *x is an int. However, *x[0] means you are saying that x[0] is a pointer which you are dereferencing. However, it isn't a pointer, it is an int. That is why there is an error.
The meaning of the array:
x[0]
is equivalent to *(x+0);
As you know array is array is nothing but pointer in its root.
So any array that has x[a] or x[a][b] can be expanded as
*(x+a) or *(*(x+a)+b)
Based on this , i hope you found your answer.

Why is the result of using `int (*p)[5]` so confusing?

I know that int (*p)[5] means a pointer which points to an array of 5 ints.
So I code this program below:
#include <iostream>
using namespace std;
int main()
{
int a[5]={0,1,2,3,4};
int (*q)[5]=&a;
cout<<a<<endl;
cout<<q<<endl;
cout<<*q<<endl;
cout<<**q<<endl;
return 0;
}
On my machine the result is:
0xbfad3608
0xbfad3608 //?__?
0xbfad3608
0
I can understand that *q means the address of a[0] and **q means the value of a[0], but why does q have the same value as a and *q? In my poor mind, it should be the address of them! I'm totally confused. Somebody please help me. Please!
Look at it this way:
q == &a
*q == a
**q == *a
You didn't try printing &a. If you do, you'll see that it has the same value as a. Since &a == a, and q == &a, and *q == a, by transitivity q == *q.
If you want to know why &a == a, check out Why is address of an array variable the same as itself?
q and &a are pointers to the array.
*q and a are "the array". But you can't really pass an array to a function (and std::ostream::operator<< is a function); you really pass a pointer to the first element, which is created implicitly (called pointer decay). So *q and a become pointers to the first element of the array.
The beginning of the array is at the same location in memory that the array is, trivially. Since none of the pointers involved are pointers-to-char (which are handled specially so that string literals will work as expected), the addresses just get printed out.
That because array is automatically converted to a pointer, which just has the value of the address of the array. So when you are trying to print print the array using <<a or <<*q, you are in fact printing its address.

Difference between the int * i and int** i

What is the difference between int* i and int** i?
Pointer to an integer value
int* i
Pointer to a pointer to an integer value
int** i
(Ie, in the second case you will require two dereferrences to access the integer's value)
int* i : i is a pointer to a object of type int
int** i : i is a pointer to a pointer to a object of type int
int*** i : i is a pointer to a pointer to a pointer to object of type int
int**** i : i is a pointer to a pointer to a pointer to a pointer to object of type int
...
int* pi
pi is a pointer to an integer
int **ppi
ppi is a pointer to a pointer to an integer.
EDIT :
You need to read a good book on pointers. I recommend Pointers on C by Kenneth Reek.
Let's say you're a teacher and have to give notes to one of your students.
int note;
Well ... I meant the whole class
int *class_note; /* class_note[0]: note for Adam; class_note[1]: note for Brian; ... */
Well ... don't forget you have several classes
int **classes_notes; /* classes_notes[0][2]: note for Charles in class 0; ... */
And, you also teach at several institutions
int ***intitute_note; /* institute_note[1][1][1]: note for David in class 1 of institute 1 */
etc, etc ...
I don't think this is specific to opencv.
int *i is declaring a pointer to an int. So i stores a memory address, and C is expecting the contents of that memory address to contain an int.
int **i is declaring a pointer to... a pointer. To an int. So i contains an address, and at that memory address, C is expecting to see another pointer. That second memory address, then, is expected to hold an int.
Do note that, while you are declaring a pointer to an int, the actual int is not allocated. So it is valid to say int *i = 23, which is saying "I have a variable and I want it to point to memory address 23 which will contain an int." But if you tried to actually read or write to memory address 23, you would probably segfault, since your program doesn't "own" that chunk of RAM. *i = 100 would segfault. (The solution is to use malloc(). Or you can make it point to an existing variable, as in int j = 5; int *i = &j)
Imagine you have a few friends, one of them has to give you something (a treasure... :-)
Say john has the treasure
int treasure = 10000; // in USD, EUR or even better, in SO rep points
If you ask directly john
int john = treasure;
int you = john;
If you cannot join john, but gill knows how to contact him,
int john = treasure;
int *gill = &john;
int you = *gill;
If you cannot even join gill, but have to contact first jake who can contact gill
int john = treasure;
int *gill = &john;
int **jake = &gill;
int you = **jake;
Etc... Pointers are only indirections.
That was my last story for today before going to bed :-)
I deeply believe that a picture is worth a thousand words. Take the following example
// Finds the first integer "I" in the sequence of N integers pointed to by "A" .
// If an integer is found, the pointer pointed to by P is set to point to
// that integer.
void f(int N, int *A, int I, int **P) {
for(int i = 0; i < N; i++)
if(A[i] == I) {
// Set the pointer pointed to by P to point to the ith integer.
*P = &A[i];
return;
}
}
So in the above, A points to the first integer in the sequence of N integers. And P points to a pointer that the caller will have the pointer to the found integer stored in.
int Is[] = { 1, 2, 3 };
int *P;
f(3, &Is[0], 2, &P);
assert(*P == 2);
&P is used to pass the address of P to the function. This address has type int **, because it's the address of a pointer to int.
int* i is the address of a memory location of an integer
int** is the address of a memory location of an address of a memory location of an integer
int* i; // i is a pointer to integer. It can hold the address of a integer variable.
int** i; // i is a pointer to pointer to integer. It can hold address of a integer pointer variable.
Neither is a declaration. Declaration syntax does not allow () around the entire declaration. What are these () doing there? If this is supposed to be a part of function declaration, include the whole function declaration thing in your question, since in general case the actual meaning of a declaration might depend on that. (Not in this one though.)
As for the difference... There is one * in the first and there are two *s in the second. Does it help? Probably not. The first one declares ias a pointer to int. The second one declares i as a pointer to int *. Does this help? Probably not much either. Without a more specific question, it is hard to provide a more meaningful answer.
Provide more context, please. Or, if this is actually as specific as it can get, read your favorite C or C++ book about pointers. Such broad generic questions is not something you ask on the net.
Note that
int *i
is not fully interchangeable with
int i[]
This can be seen in that the following will compile:
int *i = new int[5];
while this will not:
int i[] = new int[5];
For the second, you have to give it a constructor list:
int i[] = {5,2,1,6,3};
You also get some checking with the [] form:
int *i = new int[5];
int *j = &(i[1]);
delete j;
compiles warning free, while:
int i[] = {0,1,2,3,4};
int j[] = {i[1]};
delete j;
will give the warnings:
warning C4156: deletion of an array expression without using the array form of 'delete'; array form substituted
warning C4154: deletion of an array expression; conversion to pointer supplied
Both of these last two examples will crash the application, but the second version (using the [] declaration type) will give a warning that you're shooting yourself in the foot.
(Win32 console C++ project, Visual studio 2010)
Textual substitution is useful here, but beware of using it blindly as it can mislead you (as in the advanced example below).
T var; // var has type T
T* var; // var has type "pointer to T"
This works no matter what T is:
int* var; // pointer to int
char* var; // pointer to char
double* var; // pointer to double
// advanced (and not pure textual substitution):
typedef int int3[3]; // confusing: int3 has type "array (of size 3) of ints"
// also known as "int[3]"
int3* var; // pointer to "array (of size 3) of ints"
// aka "pointer to int[3]"
int (*var)[3]; // same as above, note how the array type from the typedef
// gets "unwrapped" around the declaration, using parens
// because [] has higher precedence than *
// ("int* var[3];" is an array (size 3) of pointers to int)
This works when T is itself a pointer type:
typedef int* T; // T is a synonym for "pointer to int"
T* var; // pointer to T
// which means pointer to pointer to int
// same as:
int** var;