One-dimensional array & pointer

Introduction: For a one-dimensional array, array parameters ↔ pointer variables as parameters, you can use subscript method and pointer method to refer to array elements.


1. Array parameter

? Subscript method (easy to understand)

Address: & a [i]

Element: a [i]

? Pointer method (recommended)

Earth Ruins: a + i

Element: * (a + i)

? Because the compiler interprets a [i] as * (a + i), it takes time, so directly writing a [i] as * (a + i) can improve execution efficiency


2. Pointer variables as formal parameters

? Subscript method

Address: & p [i]

Element: p [i]

? Pointer

Address: p + i

Element: * (p + i)


Two contrasts

  • p+1?p++
  1. None is simple +1, 1 refers to 1 memory unit
  2. p ++ ↔p = p + 1, the value of p changes
  3. p + 1 does not change the value of p
  • a?p
  1. a is an address constant
  2. p is an address variable

Summary: For a one-dimensional array,

In the main function, use the array name as an argument,

In the called function, the array is used as a formal parameter, and the reference element is used

Subscript method → ​​easy to understand

Pointer method → ​​Improve efficiency

? No need to use pointer variables


Examples

Array parameter

1.1 Subscript method

void InputArray(int a[], int n)   /* 形参声明为数组,输入数组元素值 */
{
	int  i;
	for (i=0; i<n; i++)
	    scanf("%d", &a[i]);       /* 用下标法访问数组元素 */	
}

void OutputArray(int a[], int n)  /* 形参声明为数组,输出数组元素值 */
{
	int  i;
	for (i=0; i<n; i++)
	    printf("%4d", a[i]);      /* 用下标法访问数组元素 */
	printf("\n");	
}

1.2 pointer method

void InputArray(int a[], int n)   /* 形参声明为数组,输入数组元素值 */
{
	int  i;
	for (i=0; i<n; i++)
		scanf("%d", a+i);          /* 这里a+i等价于&a[i] */	
}

void OutputArray(int a[], int n)   /* 形参声明为数组,输出数组元素值 */
{
	int  i;
	for (i=0; i<n; i++)
		printf("%4d", *(a+i));     /* 这里*(a+i)等价于a[i] */
	printf("\n");	
}

Pointer variables as formal parameters

1.3 Subscript method

void InputArray(int *p, int n)   /* 形参声明为指针变量,输入数组元素值 */
{	
   int i;
	for (i=0; i<n; i++)
		scanf("%d", &p[i]);      /* 形参声明为指针变量时也可以按下标方式访问数组 */       	
}

void OutputArray(int *p, int n)  /* 形参声明为指针变量,输出数组元素值 */
{
	int i;
	for (i=0; i<n; i++)
		printf("%4d",p[i]);      /* 形参声明为指针变量时也可以按下标方式访问数组 */        
	printf("\n");	
}

1.4 pointer method

void InputArray(int *p, int n)   /* 形参声明为指针变量,输入数组元素值 */
{	
	int i;
	for (i=0; i<n; i++)
		scanf("%d", p+i);        /* 用指针法访问数组元素 */	
}

void OutputArray(int *p, int n)  /* 形参声明为指针变量,输出数组元素值 */
{
	int i;
	for (i=0; i<n; i++)
		printf("%4d", *(p+i));   /* 用指针法访问数组元素 */
	printf("\n");	
}
Published 23 original articles · praised 7 · visits 1990

Guess you like

Origin blog.csdn.net/weixin_44641176/article/details/100049448