On pointers and Arrays in C (i.)

Source: Internet
Author: User

This article reprinted address: http://www.cnblogs.com/dolphin0520/archive/2011/11/09/2242138.html

On the basis of the original text to add their own ideas as a modification.

Pointers are the essence of C/s + +, and pointers and arrays are a pair of joy enemy, and many times we are not very good at distinguishing pointers and arrays, and few of the undergraduates who have just graduated from computer science have mastered the use and distinction of pointers and arrays. This may be related to the current university teaching and many C or C + + tutorials now popular in the market, although these tutorials are easy to understand, but in a lot of key places are not clear, or even explain the wrong point of view. In general, the first time to learn the C + + when exposed to this kind of tutorial, learning effect can be imagined. For beginners to choose a good tutorial is really critical, because the preconceived, once you accept the wrong point of view or thought, even if later learned it is difficult to correct it (I am deeply aware of), I recommend three this is very suitable for beginners tutorial:

"The C programming Language" Brian W. Kernighan and Dennis M. Ritchie Classics (K&r Bible)

"C + + Primer" Stanley B. Lippman, Josée Lajoie, Barbara E. Moo C + + Classic authoritative writings

"Pointers on C" Kenneth A.reek

A lot of times, someone would say "pointers and arrays are the same", which is a very dangerous argument, not entirely correct. In a certain context, pointers and arrays are equivalent, not in all cases. However, most of the time, people naturally neglect the condition of this condition and assume that it is true in all cases. The following focuses on the differences between pointers and arrays.

I. Pointer and array definitions

Pointers are pointers, pointer variables store an address that is used to indirectly access data, and a pointer variable (including a void pointer) typically occupies 4 bytes of space under a 32-bit system (some compilers account for 2 bytes). Pointers can point to any memory space, but not any memory space can be accessed by pointers.

An array is an array, and after an array is defined, the compiler opens up a contiguous amount of space in memory based on the type and number of elements of the array to hold the data, thereby directly accessing the data.

Let's look at an example

The following code is in the file1.c:

Char p[]="abcdef";

The following code is in the file2.c:

#include <stdio.h>externChar *p; int Main (void) {    printf ("%c\n", p[1]);     return0;}

Can the discovery be compiled and passed, but can it be executed correctly? Debug Discovery: This error occurred, unable to calculate the value of p[1]. The reason for this is explained later.

As can be seen from here, pointers and arrays are not identical, and the definition of an array is not equivalent to the external declaration of the pointer ( notice the difference between declaration and definition, which is defined as allocating memory space for a variable or object, and declaring simply describing the type ).

Two. Pointers and array Access differences

Reference to an array subscript:

  

Tips:
Some fields are recorded in the compiler's symbol table: the type of the address variable for the memory that corresponds to the variable identifier    each time the identifier is used in the program, the address of the memory unit corresponding to the identifier is first found, and then the data is taken from the corresponding size of the memory unit.

A reference to a pointer:

Tips:
Because P is a pointer variable, the first step is to find out what data is placed in the unit of memory for this variable, which is the same as the value of other variables of type ing. It then takes the value taken out as an address to fetch the value in the memory unit.

As you can see from the above figure, pointers and arrays are just two different things. For arrays, since the compiler already knows the address of each symbol at compile time (this address is temporary, when loading the program according to the location of the memory loaded in the relocation, but this location to be determined at compile time, so as to add this value and the value of the relocation register to complete the relocation process), So if you need an address to do something, you can do it directly, you don't need to add the instruction to get the address first, for the array, and for the pointer, you must first get its current concrete value at run time before you can reference it. From this we can explain why the above program does not execute correctly, because P defined in file1.c is an array, whereas in file2.c it declares a pointer. Therefore, when referenced in file2.c, the default p is a pointer variable, and any data in the pointer variable is treated as an address, so first the contents of the first 4 bytes of the original array are taken: 0x61 0x62 0x63 0x64 make up an address (regardless of the size of the problem) 0x61626364, and then read the contents of this address according to the Char type 0x61626364, but this address may not be a valid address, even if it is valid, is not what we want. You can think about it. What happens if p is defined as a pointer type in FILE1.C and P is declared as an array type in FILE2.C?

Test procedure:

File2.c

#include <stdio.h>#include<stdlib.h>extern Charp[];extern voidprint ();intMainvoid) {print (); printf ("%x\n", p[0]); printf ("%x\n", p[1]); printf ("%08x\n", p);//Note that the value of p at this point is the first address of the memory unit that stores the original pointer p (p in file1.c)System"Pause"); return 0;}

file1.c

#include <stdio.h>char *p="abcdef"; void print () {    printf ("%08x\n", p);    printf ("%08x\n",&p);}

The result of the execution is:

The solution to these problems is to keep the definitions and statements consistent at all times.

Three. Some areas to be aware of

1.sizeof calculates the difference between the occupied space.

For arrays, sizeof calculates the space occupied by the entire array, and the value of the sizeof pointer is always 4 under a 32-bit system.

2. The array name cannot be modified as an lvalue, and the pointer can be assigned as an lvalue.

3. The pointer can perform the self-increment (decrement) operation (except for the void pointer, since the void pointer cannot know the STRIDE size), but the array cannot be self-increment or self-decrement.
4. Understand the difference between char *p= "ABCDE" and char str[]= "ABCDE".

Specifically, for the compiler's symbol table:

  

According to the memory address of P corresponding in the table, the address of the storage string is found from the memory unit.

Based on the memory address of STR in the table, the stored string is found from the memory cell.

On pointers and Arrays in C (i.)

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.