Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning a pointer to an integer

Can I assign a pointer to an integer variable? Like the following.

int *pointer;
int array1[25];
int addressOfArray;

pointer = &array1[0];

addressOfArray = pointer;

Is it possible to do like this?

like image 409
user1293997 Avatar asked May 07 '12 20:05

user1293997


2 Answers

No, it is no valid to assign a pointer to an integer. It's a constraint violation of the assignment operator (C99, 6.5.16.1p1). A compiler has the right to refuse to translate a program with a pointer to integer assignment.

like image 77
ouah Avatar answered Sep 28 '22 05:09

ouah


Not without an explicit cast, i.e.

addressOfArray = (int) pointer;

There's also this caveat:

6.3.2.3 Pointers
...
6 Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result need not be in the range of values of any integer type.

So the result isn't guaranteed to be a meaningful integer value.

like image 21
John Bode Avatar answered Sep 28 '22 06:09

John Bode