Can 2.2 arrays and pointers be the same?11 A lot of people will do wrong face questions Look at the following code carefully, PRINT_ARR_ADDR and print_g_arr_addr have the same printout address. Why
#include <stdio.h>
int a[10] = {1, 3, 4};
void print_arr_addr (int *p)
{
printf ("&p = 0x%08x.\n", (unsigned) &p);
printf ("&p[0] = 0x%08x.\n", (unsigned) &p[0]);
void Print_g_arr_addr ()
{
printf ("&a = 0x%08x.\n", (unsigned) &a);
printf ("&a[0] = 0x%08x.\n", (unsigned) &a[0]);
int main ()
{
print_arr_addr (a);
Print_g_arr_addr ();
return 0;
}
Here I do not say the answer, I believe that after reading this article will, naturally understand why. 2 array and pointer differences 2.1 arrays and pointers are how to access the definitions and declarations of 2.1.1 arrays and pointers
Here it is necessary to list the differences between declarations and definitions: definition: can only appear in one place, it will allocate memory declarations for objects: can appear in multiple places, describing the type of object, used to refer to objects defined elsewhere
X is a declaration extern int *x that points to an int type pointer
;
Y is an int-type array declaration
extern int y[];
Defines the pointer x
int *x;
Define array y
int y[10];
Array subscript Reference: An array can directly access the data, if we define an array int a[, and the address of A and a[0] are the same.
Pointer subscript Reference: refers to access to data is actually indirect access, int * p, P's address and p[0] address is absolutely different
In general, pointers take more steps from memory than arrays, and one step is to get to the site. The address of the array is the address of the first element of the array, so the array does not need this step. can 2.2 arrays and pointers be the same?
Arrays and pointers are, of course, equivalent in some cases:
An array declaration is equivalent to a pointer declaration when it is used as a parameter of a function. You can choose the array method or the pointer mode as you like. When used in an expression, subscript access is also equivalent to arrays and pointers, C = a[i], regardless of whether a declares an array or a pointer. 3 Summary for definitions and declarations, arrays and pointers are different and defined as arrays, the declaration should also be an array, and if mixed use would appear unexpected errors. The array and the pointer are equivalent when using the subscript operator to perform an operation on the arrays and pointers. a[i] will be translated into the form of * (A+i) by the compiler. When an array declaration is used as a function parameter, the array is actually used as a pointer.
Author:elvin, huang
date:2014-12-29 21:55:58
HTML generated by Org-mode 6.31a in Emacs 23