Skip to content

Instantly share code, notes, and snippets.

@ziyoung
Last active April 29, 2019 10:09
Show Gist options
  • Save ziyoung/8affd8b93ca8e9a9fecc91c61bd25678 to your computer and use it in GitHub Desktop.
Save ziyoung/8affd8b93ca8e9a9fecc91c61bd25678 to your computer and use it in GitHub Desktop.
数组与指针的关系

指针的介绍

  • 指针仅仅是指向计算机中的某个地址,并带有类型限定符。
  • 你可以对一个指针使用数组的语法来访问指向的东西,也可以对数组的名字做指针的算数运算。
  • 你应该每次尽可能使用数组,并且按需将指针用作提升性能的手段。

指针并不是数组

无论怎么样,你都不应该把指针和数组混为一谈。它们并不是相同的东西,即使C让你以一些相同的方法来使用它们

除了sizeof、&操作和声明之外,数组名称都会被编译器推导为指向其首个元素的指针。对于这些情况,不要用“是”这个词,而是要用“推导”。

#include <stdio.h>
int main(int argc, char *argv[])
{
int ages[] = {23, 43, 12, 89, 2};
char *names[] = {"Alan", "Frank", "Mary", "John", "Lisa"};
int count = sizeof(ages) / sizeof(int);
int i;
// 1. 最原始的方式:通过数组+下标访问
for (i = 0; i < count; i++)
{
printf("%s has %d years alive.\n",
names[i],
ages[i]);
}
printf("-------------------\n");
int *cur_age = ages;
char **cur_name = names;
// 2. 通过对直接进行偏移访问元素
for (i = 0; i < count; i++)
{
printf("%s is %d years alive.\n",
*(cur_name + i),
*(cur_age + i));
}
printf("-------------------\n");
// 3. 把数组直接作为指针来访问
for (i = 0; i < count; i++)
{
printf("%s has %d years alive.\n",
cur_name[i],
cur_age[i]);
}
printf("-------------------\n");
// 4. 通过对进行运算来访问
for (cur_name = names, cur_age = ages;
(cur_age - ages) < count;
cur_age++, cur_name++)
{
printf("%s is %d years alive.\n",
*cur_name,
*cur_age);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment