C ++ refers to histogram profiling (2)

Source: Internet
Author: User

I. Definition of pointers and Arrays

Pointers are pointers, and pointer variables store an address for indirect data access. In a 32-bit system, a pointer variable (including void pointers) always occupies 4 bytes of space. Pointers can point to any memory space, but not any memory space can be accessed through pointers.

An array is an array. After defining an array, the compiler will open up a continuous space in the memory to store data based on the type and number of the array elements, so as to directly access the data.

The following is an example.

The following code is available in file1.c:

char p[100]="abcdef";

The following code is available in file2.c:

#include<stdio.h>

extern char *p;

int main(void)
{
printf("%c\n",p[1]);
return 0;
}
Copy code

Can it be compiled but executed correctly? Debugging found: this error occurs and the value of P [1] cannot be calculated. The cause will be explained later.

From this we can see that the pointer and the array are not equivalent, and the definition of the array is not equivalent to the external Declaration of the pointer (note the difference between the Declaration and definition, the definition is to allocate memory space for a variable or object, and the declaration is only a description type ).

Ii. Differences between pointer and array access

References to the array objects:


Pointer Reference:

From the figure above, we can see that pointers and arrays are totally different. For arrays, since the compiler knows the address of each symbol during compilation, if you need an address to perform some operation, you can directly perform the operation, you do not need to add a command to obtain the specific address first, as for arrays. For pointers, you must first obtain the specific value of the pointer at runtime before reference. From this point, we can explain why the above program cannot be correctly executed, because the P defined in file1.c is an array, but it is declared as a pointer in file2.c. Therefore, in file2.c, P is a pointer variable by default, and any data in the pointer variable is processed as an address. Therefore, the first four bytes of the original array are obtained: 0x61 0x62 0x63 0x64 constitute an address (not considering the size of the end) 0x61626364, and then read the content in the address 0x61626364 according to the char type, but this address may not be a valid address, even if it is valid, it is not what we want. If we define P as the pointer type in file1.c and declare P as the array type in file2.c, what will happen?

The solution to the above problems is to maintain consistency between definitions and declarations at any time.

Test procedure:

File2.c

# Include <stdio. h>

Extern char P [];
Extern void print ();

Int main (void)
{
Printf ("% x \ n", P [0]);
Printf ("% x \ n", P [1]);
Printf ("% 08x \ n", P); // note that the value of P is the first address of the memory unit storing the original pointer P (P in file1.c ).
Print ();
Return 0;
}
Copy code

File1.c

#include<stdio.h>
char *p="abcdef";

void print()
{
printf("%08x\n",p);
printf("%08x\n",&p);
}
Copy code

The execution result is:

28
20
0020.a30
0020.a30
00422028
0020.a30
Press any key to continue

3. Notes

1. What is the difference between sizeof computing space.

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

2. When the array name is used as the left value, it cannot be modified, and when the pointer is used as the left value, it can be assigned a value.

3. the pointer can perform auto-increment (auto-subtraction) Operations (except for the void pointer, because the void pointer cannot know the step size), but the array cannot perform auto-increment or auto-increment operations.
4. Understand the differences between char * P = "ABCDE" and char STR [] = "ABCDE.

 

We have discussed some differences between pointers and arrays. However, in some cases, pointers and arrays are equivalent. Next we will discuss when pointers and arrays are the same.

C language standards are described as follows:

Rule 1: the array name in the expression is treated as a pointer to the first element of the array by the compiler;

Note: exceptions in the following situations

1) array name as the operand of sizeof

2) use the & retrieve array address

Rule 2: The subscript is always the same as the pointer offset;

Rule 3: In the declaration of function parameters, the array name is treated as a pointer to the first element of the array by the compiler.

The combination of rule 1 and rule 2 means that the reference to the array subject can always be written as "a pointer pointing to the starting address of the array plus an offset ". For example, a [I] is always parsed as * (a + I) by the compiler.

 

Rule 1: The array name in the expression is always parsed as a pointer by the compiler, so the following statement int A [3]; int * P = A; can be correctly compiled and executed. In the expression, expression A is parsed as a pointer to the first element of the array, so the types on both sides of the value assignment symbol match, so you can compile and execute correctly.

Rule 2: The subscript is always the same as the pointer offset. In C, the subscript of the array is rewritten to the pointer offset mainly because the pointer and offset are the basic types used by the underlying hardware. For example, I in a [I] is always parsed as an offset by the compiler, so a [I] is always rewritten into the form of * (a + I, A is the pointer pointing to the first element of the array. The offset I is used to move the pointer to the next step and then take the content of the unit where a + I is located. This explains why the subscript of the array in C can be negative, and in my opinion, the C language does not check whether the subscript of the array is out of the range, as shown in the following program:

#include<stdio.h>

int main(void)
{
int a[3]={1,2,3};
int *p=(a+3);
printf("%d\n",p[-1]);
return 0;
}
Copy code

The execution result of the program is 3. Although the subscript is-1, it is parsed as an offset by the compiler, so it is equivalent to P-1 ).

Rule 3: In the declaration of function parameters, the array name is treated as a pointer to the first element of the array by the compiler. In C language, it is out of efficiency considerations to equate the arrays and pointers of form parameters. If this is not done, the values of each element in the entire array are copied and transmitted, so that the overhead in both time and space may be very large. However, to operate on elements in the array, you only need to pass the address of the first element of the array to the calling function, and then access the space to be accessed through the pointer. This will greatly reduce the space-time consumption. Therefore, in a function, the compiler always treats the array name declared in the parameter as a pointer to the first element of the array. In this way, the compiler can generate the correct code, no need to distinguish between arrays and pointers. Therefore, void fun (int A []); and void fun (int * A) have the same effect. If a is referenced in the function, always considered as a pointer by the compiler. Because void fun (int A []); this form will eventually be parsed by the compiler as void fun (int * ); this method tells us that a pointer to the integer data must be passed during the call. Therefore, the following code can be correctly compiled and executed:

#include<stdio.h>

void fun(int a[])
{
printf("%d\n",a[0]);
}
int main(void)
{
int a[3]={1,2,3};
int *p1,*p2;
int b=4;
p1=a;
p2=&b;
fun(a);
fun(&a[1]);
fun(p1);
fun(p2);
fun(&b);
return 0;
}
Copy code

Differentiate the meanings of several expressions:

& P, P, A, &

& P: the address of the memory unit that obtains the storage pointer Variable P; sizeof (& P) = 4;

P: the address where the pointer Variable P is stored; sizeof (p) = 4;

A: The address of the first element of the array. sizeof (A) = 3*4 = 12;

& A: The first address of the entire array. sizeof (& A) = 4 (in VC ++ 6.0, this value is 12. I think it is incorrect, because its type is array pointer)

Although the values of a and & A are the same, their meanings are completely different. A indicates that the address of the first element of the array is obtained, and & A indicates that the first address of the array is obtained. The types they represent are also completely different. A is an int pointer, and & A is an int (* P) [] pointer, that is, the array pointer (which will be explained in subsequent articles ). Therefore, the results of a + 1 and & A + 1 are different, A + 1 indicates moving the pointer to the first element of the array to the back of a step (the step here is the number of bytes occupied by the array element type ); & A + 1 indicates moving the pointer pointing to the array backward by a step (and the step here is the number of array elements * The number of bytes occupied by the element type ).

# Include <stdio. h>

Int main (void)
{
Int A [3] = {1, 2, 3 };
Int * P =;
Printf ("% 08x \ n", & P );
Printf ("% 08x \ n", P );
Printf ("% 08x \ n", & P + 1 );
Printf ("% 08x \ n", p + 1 );
Printf ("% 08x \ n", );
Printf ("% 08x \ n", & );
Printf ("% 08x \ n", A + 1 );
Printf ("% 08x \ n", & A + 1); // pay attention to the output result
Return 0;
}

 

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.