Assigning a pointer to an integer

前端 未结 5 1984
[愿得一人]
[愿得一人] 2020-12-07 02:48

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

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

pointer = &array1[0];

addressOfAr         


        
5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-07 03:23

    Nope.

    You are attempting to assign a "pointer to int" value to an "int" variable. You will get a compiler warning for sure. You could do:

    int *pointer;
    int array1[25];
    int *addressOfArray;
    
    pointer = &array1[0];
    //The following commented lines are equivalent to the pointer assignment above and are also valid
    //pointer = array
    //pointer = &array[0]
    
    addressOfArray = pointer;
    

    This is known as a shallow copy. If you are not already familiar with the concept, I highly recommend you read it (Google "deep vs shallow copying").

提交回复
热议问题