简体   繁体   中英

Assigning Pointers to Variables vs Assigning Pointers to Arrays in C

Hey guys I am reading over pointers in C at tutorialspoint.com

However some inconsistency assigning an address to a pointer have me confused.

Take this two examples:

/* Assigning address of variable to a pointer */
int  var = 20;   
int  *ip;        
ip = &var;  

/* Assigning address of an array to a pointer */
int  array[] = {10, 100, 200};
int  *ptr;
ptr = array;

Why do we assign an address of a variable like this ip = &var. But when we assign an address of an array the '&' character is missing, ex: ptr = array.

Could anybody clarify this confusion? This examples where taken from tutorialspoint.com

This is because in C programming, name of the array always points to address of the first element of an array.

update with example:

For example: int arr[4];

在此处输入图片说明

arr and &arr[0] points to first element.

Since, the addresses of both are same, values of arr and &arr[0] are also the same.

When you initialize an array like 'int arr[]' the name of the array 'arr' points to the first element of the array. So basically arr==&arr[0].This is particularly useful in programming as while sending values of an array only the first element's address is sent and the rest of the element's address are linked to the first element's address. Elements in an array can therefore be accessed by *(arr+i) where 'i' denotes the index of the element.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM