Why can't I assign the int variable i to the int pointer *ip? They are both int
Why can't I assign the int variable i to the int pointer *ip? They are both int
I'm new to Java. I'm trying to learn the concept of pointer and reference. Could someone please explain to me why the code below is illegal? Why can't I assign the int variable i to the int pointer *ip? They are both int. I'm really struggling with the concept. Thanks in advance for any help!
int i = 0; int *ip = i;
Answer by VolAnd for Why can't I assign the int variable i to the int pointer *ip? They are both int
In case
int *ip = i;
you actually assign value 0
to pointer. I.e. ip
has type int *
- pointer to int
, and it is not int
. If you want assign 0
to pointer use
int *ip = NULL; // good way
or
int *ip = (int *)i; // incorrect pointer initialization with explicit type conversion
In general, assignment to pointer have to be NULL
or address of allocated memory (allocated with new
or malloc
or address of existing variable taken with unary &
operator), e.g.
int *ip = NULL; ip = &i; // address of variable ip = malloc(sizeof(int)); // allocation in C style ip = new int; // allocation in C++ style
then value can be assigned to allocated memory with pointer as follows:
*ip = i; // here pointer value (address) is not changed
To see address (value of pointer) and pointed value test that statement:
std::cout << "Adress " << ip << " contains value " << *ip << std::endl;
Answer by SnG for Why can't I assign the int variable i to the int pointer *ip? They are both int
int *ip
is a variable known as a pointer that could hold a memory address of a variable of type int
. i
is of type int
, so to use the pointer correctly, type
int *ip = &i;
which assigns the pointer ip
to the memory address of i
Answer by Harpo Roeder for Why can't I assign the int variable i to the int pointer *ip? They are both int
You can like this:
int i = 0; int* ip = 5; *ip = i;
Answer by Chaudhari Mahendra for Why can't I assign the int variable i to the int pointer *ip? They are both int
ip is a pointer and pointer must be hold the address of another variable.
int i = 0; int *ip; ip = &i;
or
int *ip = &i;
Answer by Asesh for Why can't I assign the int variable i to the int pointer *ip? They are both int
You have to either initialize that pointer or assign a valid memory address to it. This will assign the address of 'i' to ip
int *ip = &i;
You could also do this:
int *ip = new int(12); std::cout<<*ip<
Output:
12
Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72
0 comments:
Post a Comment