C language pointers and arrays based on the cornerstone and practice of programming

Source: Internet
Author: User

English Source: Dennis kubes: Basicsofpointers and Arrays in C.


The argument about pointers and arrays in the C language is like a tough game. On the one hand, some people feel that everyone must admit that pointers are different from arrays. Others think that arrays are treated as pointers, so they should not be different. This phenomenon is confusing to people. However, both of these statements are true.

Arrays are not pointers, and pointers are not arrays. In the C language, pointers represent only one address in memory, and arrays are many contiguous blocks of memory, where multiple types of similar elements are stored. For more in-depth explanations, please refer to my previous blog "C memory Address". In most cases of C language, arrays are treated as pointers, which is also confusing.

array notation vs pointer notation

The array is treated as a pointer, referring to the following two articles:

    • The array name variable represents the address of the first element in the array. It is not a pointer, but behaves like a constant pointer that cannot be modified.
    • When the program interacts with the array, the pointer notation is used instead of the array notation.

Let's look at some code.

Initialize an array of intsint numbers[5] = {1,2,3,4,5};//standard array notationint *ptr1 = numbers;int Val1 = number s[0];//address of array notationint *ptr2 = &numbers[0];int val2 = * (&numbers[0]);//pointer + increment notation int *PTR3 = numbers + 0;int val3 = * (numbers + 0);//print out the address stored in the pointersprintf ("*PTR1 =%p\n", (V OID *) ptr1);p rintf ("*PTR2 =%p\n", (void *) PTR2);p rintf ("*PTR3 =%p\n", (void *) PTR3);//print out the value at the Pointe R addressesprintf ("Val1 =%d\n", val1);p rintf ("val2 =%d\n", val1);p rintf ("Val3 =%d\n", val1);
We declare an array containing 5 int, and assign the array name variable numbers to an int pointer, PTR1. Numbers represents the address of the first element of the array and assigns it to PTR1 as a pointer to use. We then use array notation to access the value of the first element.

In the second example, we used the array notation to take the address of the first element in the array, and then we accessed it using the method that referred to the address of the first element.

In the third example, we use pointer arithmetic to assign the address of the first element in the array to PTR3, after which we dereference the same address to get its value.

Finally, we output all the addresses stored in the pointer and all the int values at those addresses to the screen. Run this code and you will get output similar to the following:

*PTR1 = 0X7FFF6BE1DE60*PTR2 = 0X7FFF6BE1DE60*PTR3 = 0x7fff6be1de60val1 = 1val2 = 1val3 = 1
all values are the same. Then look at the following code:

Initialize an array of intsint numbers[5] = {1,2,3,4,5};int i = 0;//print out elements using array notationfor (i = 0; I < 5; i++) {  int value = Numbers[i];  printf ("numbers[%d] =%d\n", I, value);} Print out elements using pointer math + array indexing (yuck!) for (i = 0; i < 5; i++) {  int value = * (numbers + i);  printf ("* (numbers +%d) =%d\n", I, value);} Print out elements using a single pointerint *ptr = numbers;for (i = 0; i < 5; i++) {  int value = *ptr++;  printf ("%d, *ptr++ =%d\n", I, value);}
Run it and you will get the following output:

Numbers[0] = 1numbers[1] = 2numbers[2] = 3numbers[3] = 4numbers[4] = 5* (numbers + 0) = 1* (numbers + 1) = (numbers + 2) = * * (numbers + 3) = numbers + 4) =, *ptr++ = one, *ptr++ = 5, *ptr++ = =, *ptr++ = *ptr++

As you can see, all the processes get the same results.

Array notation is actually a pointer operation. The C language standard simply defines numbers[0] as the syntactic sugar of * (numbers + 0). (Translator notes: Grammatical sugars, which mean the grammar that does not add new functionality to the computer language, but is easier for humans to understand.) Whenever you write an array notation, say numbers[2], it will be converted to * (numbers + 2) by the compiler. Here, numbers represents the address of the first element in the array, and +2 represents the offset used for the pointer operation.

Array Variables

We have shown that arrays are often treated as pointers, and array notation is a pointer operation for the C compiler. Some people naturally make the assumption that, since arrays can be treated as pointers, pointers should also be able to assign values to arrays. This is not correct, and the array name variable cannot be changed. Let's take a look at the code below.

Initialize an array of intsint numbers[5] = {1,2,3,4,5};int Numbers2[5] = {6,7,8,9,0};int *ptr = numbers2;//This won ' t Compilenumbers = Numbers2;numbers = &numbers2;numbers = ptr;
This code cannot be compiled. Give it a try and you'll get the following output.

incompatible types when assigning to type ' int[5 "' from type ' int * ' incompatible types when assigning to type ' int[5] ' fro M type ' int (*) [5] ' incompatible types when assigning to type ' int[5] ' from type ' int * '

Although the array name variable represents the address of the first element of the array, it behaves like a constant pointer that cannot be changed. It cannot accept an assignment of another array name variable or a pointer to another array. Think about it, if you have an array name variable A that represents an array, and you can change the address of a, what happens to the memory that is pointed to by a?

Next look at the code that compiles.

Initialize an array of intsint numbers[5] = {1,2,3,4,5};int Numbers2[5] = {6,7,8,9,0};int *PTR1 = Numbers;int *PTR2 = n  umbers2;//this would compileptr1 = ptr2;//print the addressesprintf ("numbers =%p\n", (void *) numbers);p rintf ("numbers2 = %p\n ", (void *) numbers2);p rintf (" ptr1 =%p\n ", (void *) PTR1);p rintf (" PTR2 =%p\n ", (void *) PTR2);
它会输出这样的结果:

Numbers = 0x7fff5ea3d230numbers2 = 0X7FFF5EA3D250PTR1 = 0X7FFF5EA3D250PTR2 = 0x7fff5ea3d250

Although the array name variable cannot be changed directly, we still change a pointer to the array. In the code, we created two arrays, two int pointers. We gave the numbers to PTR1 and gave numbers2 to PTR2. Then we assign the PTR2 to the PTR1, and the final output results. As you can see, both PTR1 and Ptr2 point to the first element of the NUMBERS2 array.

Summarize

I want you to enjoy this overview of arrays and pointers in C. We did not include all the knowledge about pointers and arrays, but it was enough to start with. As always, I am very willing to accept the comments and suggestions from you.



For more discussion and exchange on the cornerstone and practice of program design, please follow this blog and Sina Weibo songzi_tea.

C language pointers and arrays based on the cornerstone and practice of programming

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.