Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it a compile error to assign the address of an array to a pointer "my_pointer = &my_array"?

Tags:

c++

arrays

int my_array[5] = {0};
int *my_pointer = 0;

my_pointer = &my_array;  // compiler error
my_pointer = my_array;   // ok

If my_array is address of array then what does &my_array gives me?

I get the following compiler error:

error: cannot convert 'int (*)[5]' to 'int*' in assignment

like image 851
user74564 Avatar asked May 10 '11 21:05

user74564


People also ask

How do I add an address to a pointer?

To access address of a variable to a pointer, we use the unary operator & (ampersand) that returns the address of that variable. For example &x gives us address of variable x.

Can you change the address pointed to by an array variable?

You cannot swap the address of array elements. The array elements are all stored in sequence in memory. If an integer takes 4 bytes in memory, for an array of size 10, a total of 40 contiguous bytes are taken in memory.

Can you assign an array to a pointer?

Array VariablesIt cannot be assigned a different array or a pointer to a different array. Think about it, if you have a variable A that points to an array and you were able to change the address of A to something else, what happens to the memory pointed to by the A array.

Why do we need array of pointers?

An array of pointers is useful for the same reason that all arrays are useful: it lets you numerically index a large set of variables. Below is an array of pointers in C that points each pointer in one array to an integer in another array. The value of each integer is printed by dereferencing the pointers.


1 Answers

my_array is the name of an array of 5 integers. The compiler will happily convert it to a pointer to a single integer.

&my_array is a pointer to an array of 5 integers. The compiler will not treat an array of integers as a single integer, thus it refuses to make the conversion.

like image 128
Mark Ransom Avatar answered Oct 03 '22 22:10

Mark Ransom