Use pointers to access arrays in C

Source: Internet
Author: User

If pa points to an element in the array, pa + 1 points to the next element, and pa + I points to the next element. Therefore, if pa points to a [0], * pa is actually a [0], * (pa + 1) is a [1], * (pa + I) is a [I]. Based on this idea, we can use pointers to access arrays.

# Include <stdio. h> int main (int argc, char * argv []) {int score [10] = {,}; int wait, length, I; length = sizeof (score)/sizeof (score [0]); for (I = 0; I <length; I ++) {printf ("% d \ n ", * (score + I);} scanf ("% d", & wait );}

Program output:

76859067597982959165

The array subscript is closely related to the pointer. After the execution of the statement pa = & a [0], the pa and a have the same value, and * pa = a [0]. In fact, the C language uses pointers to calculate the array downlink. Subscript is equivalent to pointer.

When an array name is passed to a function, the address of the first element of the array is actually passed. Therefore, the array name parameter must be a pointer.

Programs that calculate the string length can be written as follows:

Int strlen (char * s) {int n; for (n = 0; * s! = '\ 0'; s ++) n ++; return n ;}

S is a pointer, that is, a variable. It is valid to perform auto-increment on it.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.