I am new at C++. Just got started with it. The problem I am having is again and again saying cannot convert int**
to int*
.
I know that in the compiler the arrays are interpreted the same as pointers, so is it true that if I am to write a[]
then it'll be interpreted as a*
and if I write a[]
where a
is of the datatype int*
, then it'll be interpreted as int**
?
The problem I am having is again and again saying cannot convert
int**
toint*
.
Which is a problem that can be reduced to the fact that a dereferenced int**
(an int*
) is not a dereferenced int*
(an int
).
Pointers and int
s can be quite different , depending on your compiler and your machine. They don't even need to have the same size.
Just how is this is a "problem", exactly?
I know that in the compiler the arrays are interpreted the same as pointers,
That's a very simplifying statement. An array can be interpreted as a pointer to its first element . A common case where this happens is when people try to pass arrays by value to a function, which the language does not allow.
The following functions are indeed identical:
void f(int a[])
{
int first_element = a[0];
int first_element_too = *a;
}
void f(int* a) // identical
{
int first_element = a[0];
int first_element_too = *a;
}
(Your linker will even complain about a redefinition if you try this.)
so is it true that if I am to write
a[]
then it'll be interpreted asa*
I think you mean if you write int a[]
then it's as if you wrote int* a
?
Under certain circumstances.
and if I write
a[]
wherea
is of the datatypeint*
,
That's impossible. If you write a[]
, then it's part of a declaration, so a
is not of type int*
but of an array type.
I think what you really mean is an array of int*
elements, ie an int* a[]
.
then it'll be interpreted as
int**
?
Under certain circumstances. Again, a typical case would be the attempt to pass the array by value:
void f(int* a[])
{
int* first_element = a[0];
int* first_element_too = *a;
}
void f(int** a) // identical
{
int* first_element = a[0];
int* first_element_too = *a;
}
Note how these two functions do not attempt to convert an int**
to an int*
. The int*
is the first element .
By the way, while it certainly cannot hurt to study these low-level basics of C++, you should use std::array
and std::vector
in real code.
Array is a contiguous memory of bytes.
Pointer is a few bytes which holds a memory address of other variable.
Array != Pointer.
although they are not the same , they share some link :
so this applies:
int arr[3];
arr == &arr[0]; //true
void f (int arr[4])
is the same as
void f(int* arr)
int* arr = new int[4];
so array can be expressed as pointer when one of the conditions above applies.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.