C Language Study-form of the pointer & subscript

Source: Internet
Author: User

Pointer form and subscript form

a> char *p = "abcdef";//defines a string that points to the string with a pointer

B>char a[] = "123456";//define a character array A is the first address of the first element of the array, not the first address of the array

In the a> definition above, if we want to remove the C character, then there are two ways:

<1> the form of the pointer: * (P+3)

<2> subscript form: p[3]

There are two ways that we can understand this:

The compiler first calculates The value of P, which is the address value stored by P, and then an offset of 3, to get a new address,

And then take out the data stored in the new address, which is the character C.

For example, you can write out the following program to output a string defined in a>.

#include <stdio.h>int main (void) {    char *p= "abcdef";//a>    int ioffset = 0;    For (Ioffset=0;ioffset<strlen (p); ioffset++)        printf ("%c", * (P+ioffset));    return 0;}
Similarly, in the b> definition, if we want to take out 5 of this data, there are two ways:

<1> the form of the pointer: * (A+4); At this point, a represents the first address of the first element of the array, and then uses this address to add an offset,

Get a new address and fetch the data from this address

<2> the form of subscript: a[4];


It is worth noting that, without knowing what you have found, there is a problem with the above mentioned offset, after removing the base address (P-value in a> in,b>, a addresses),

The offset should be the number of offsets x the size of each element. In the example above, the memory size of the character type is exactly 1, so it is easy to mislead. Special attention!




C Language Study-form of the pointer & subscript

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.