C language FAQ list

Source: Internet
Author: User

 

6.13

 

Http://c-faq.com/aryptr/ptrtoarray.html

 

Q: How can I define a pointer to an array?

 

A: Generally, when talking about pointers to arrays, it actually refers to a pointer to the first element of an array. For example:

 

Int arr [3] = {1, 2, 3 };

Int * PTR = arr;

Printf ("* PTR = % d/N", * PTR); // * PTR = 1

 

Strictly speaking, the PTR here is actually a pointer to the first element 1 of the array arr, rather than an array pointer, that is, PTR is an int * type pointer, we can perform algebraic operations on PTR, such as auto-increment:

 

PTR ++;

Printf ("* PTR = % d/N", * PTR); // * PTR = 2

 

When the array name arr is assigned to PTR:

PTR = arr;

The function is equivalent to the following sentence:

PTR = & arr [0] l

 

If you want the PTR to point to ARR [1], it should be as follows:

PTR = & arr [1];

 

Okay, now we will discuss the pointer to the array instead of the pointer to a single element of the array. For example, we need to define a pointer to an int-type array with a size of 3, it should be defined as follows:

 

INT (* ptrarr) [3];

 

When ptrarr ++ is used, the distance ptrarr spans is 3 rather than 1. Generally, the true array pointer is used only when multiple arrays are operated:

 

INT (* ptrarr) [3];

Int arr [2] [3] = {3, 4, 5}, {6, 7, 8 }};

Ptrarr = arr;

Printf ("(* ptrarr) [0] = % d, (* ptrarr) [1] = % d/N", (* ptrarr) [0], (* ptrarr) [1]); // (* ptrarr) [0] = 3, (* ptrarr) [1] = 4

 

Ptrarr ++; // The distance between ptrarr and ptrarr is 3!

Printf ("(* ptrarr) [0] = % d, (* ptrarr) [1] = % d/N", (* ptrarr) [0], (* ptrarr) [1]); // (* ptrarr) [0] = 6, (* ptrarr) [1] = 7

 

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.