简单分析C语言中指针数组与数组指针的区别

时间:2021-09-26 08:33:38

首先来分别看一下,指针数组的一个小例子:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <stdio.h>
#include <string.h>
 
int lookup_keyword(const char*key, const char* table[], const int size)
{
  int ret = -1;
 
  int i = 0;
 
  for(i=0; i<size; i++)
  {
    if (strcmp(key, table[i]) == 0)
    {
      ret = i;
      break;
    }
  }
  return ret;
}
 
#define DIM(array) (sizeof(array)/sizeof(*array))
 
int main()
{
  const char* keyword[] = {
      "do",
      "for",
      "if",
      "register",
      "switch",
      "while",
      "case",
      "static",
  };
 
  printf("%d\n", lookup_keyword("static", keyword, DIM(keyword)));
 
  return 0;
}

数组指针

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <stdio.h>
 
int main()
{
  int i;
  int* pI = &i; //普通类型
 
  typedef int(AINT5)[5];
  AINT5* p1;
  int array[5];
  p1 = &array; //数组指针1
 
  int (*p2)[5] = &array; //数组指针2(不建议这样写)
 
  int (*p3)[4] = &array; // X 数组指针3(不建议这样写)
 
  return 0;
}

 

这两个名字不同当然所代表的意思也就不同。我刚开始看到这就吓到了,主要是中文太博大精深了,整这样的简称太专业了,把人都绕晕了。从英文解释或中文全称看就比较容易理解。

指针数组:array of pointers,即用于存储指针的数组,也就是数组元素都是指针

数组指针:a pointer to an array,即指向数组的指针

还要注意的是他们用法的区别,下面举例说明。

int* a[4]     指针数组    

                 表示:数组a中的元素都为int型指针   

                 元素表示:*a[i]   *(a[i])是一样的,因为[]优先级高于*

int (*a)[4]   数组指针    

                 表示:指向数组a的指针

                 元素表示:(*a)[i] 

注意:在实际应用中,对于指针数组,我们经常这样使用:

?
1
2
typedef int* pInt;
pInt a[4];

这跟上面指针数组定义所表达的意思是一样的,只不过采取了类型变换。

代码演示如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
 
using namespace std;
 
int main()
{
int c[4]={1,2,3,4};
int *a[4]; //指针数组
int (*b)[4]; //数组指针
b=&c;
//将数组c中元素赋给数组a
for(int i=0;i<4;i++)
{
a[i]=&c[i];
}
//输出看下结果
cout<<*a[1]<<endl; //输出2就对
cout<<(*b)[2]<<endl; //输出3就对
return 0;
}

注意:定义了数组指针,该指针指向这个数组的首地址,必须给指针指定一个地址,容易犯的错得就是,不给b地址,直接用(*b)[i]=c[i]给数组b中元素赋值,这时数组指针不知道指向哪里,调试时可能没错,但运行时肯定出现问题,使用指针时要注意这个问题。但为什么a就不用给他地址呢,a的元素是指针,实际上for循环内已经给数组a中元素指定地址了。但若在for循环内写*a[i]=c[i],这同样会出问题。总之一句话,定义了指针一定要知道指针指向哪里,不然要悲剧。