I tried the below-pasted code and got an error:
cannot convert
int (*)[6]
toint*
in assignment
compilation terminated due to-Wfatal-errors
.
#include <stdio.h>
int my_array[] = {1,23,17,4,-5,100};
int *ptr;
int main(void)
{
int i;
ptr = &my_array; /* point our pointer to the first
element of the array */
printf("\n");
for (i = 0; i < 6; i++)
{
printf("my_array[%d] = %d ",i,my_array[i]); /*<-- A */
printf("ptr + %d = %d\n",i, *(ptr + i)); /*<-- B */
}
return 0;
}
ptr = &my_array;
The type of &my_array
is int (*)[6]
while the type of ptr
is int*
. They're incompatible types.
What you should be doing is this:
ptr = my_array;
Now the type my_array
is int[6]
which decays into int*
in the above context. So it works.
An array is convertible to a pointer. What you meant to do is:
ptr = my_array;
You have to use:
ptr = my_array;
Which is equivalent to:
ptr = &my_array[0];
All you need to do here is:
ptr = my_array;
There's no need to use the &
operator.
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.