我发现了一个指向数组的指针的示例,这对我来说没有多大意义,我想知道是否有人能够帮助我?
int a[5] = 0,1,4,89,6;
int *p = a; 'p points at the start of a'
p[3] = 1; 'a[3] is now 6'
我不确定第三行 p[3] = 1 是如何工作的以及它如何导致 a[3] = 6。提前感谢您的帮助。
最佳答案
有点不正确。 a[3]
是 1
,而不是 6
。
以下是逐行解释:
int a[5] = 0,1,4,89,6;
int *p = a; //'p points at the start of a'
p[3] = 1; //'a[3] is now 1 not 6'
第一行初始化数组。我认为数字周围应该有 {},但如果与你一起编译就可以了。我认为应该是这样的:
int a[5] = {0,1,4,89,6};
第二行创建指向 int p
的指针并将其初始化为 a
的地址。数组和指针在 C 中密切相关,因此现在有 2 个变量 a
和 p
指向同一个内存地址。
第三行 - 您将 p[3]
设置为 1
,这次您将 p
作为 int 数组访问(这是可能的,因为数组和指针之间的关系)。因为 p
和 a
指向相同的内存地址,这意味着 a[3]
现在是 1
另外备注也不正确,必须是/* */或//。
更新:
David 的评论非常重要。
数组是连续保留的内存,能够存储多个数组值,在您的例子中是 5 个 int。
指针就是指针,可以指向任何可以指向 int 变量的地方:
int a = 5;
int *b = &a;
或者它们可以像您的情况一样指向数组。在这两种情况下,您都可以使用 [],但如果它指向单个值,则任何大于零的数组下标都将是错误的,例如
int a = 5;
int *b = &a;
*b = 4; // OK.
b[0] = 4; // OK.
b[1] = 4; // compiles correctly, but is **wrong**.
// it will overwrite something in memory
// and if program not crash,
// it will be security hole.
int x[10];
int *y = x;
*y = 4; // works correctly for y[0],
// but makes it difficult to read.
y[0] = 5; // OK
y[9] = 5; // OK
y[10] = 5; // compiles correctly, but is **wrong**.
// it is after last element of x.
// this is called **buffer overflow**.
// it will overwrite something in memory
// and if program not crash,
// it will be security hole.
更新:
我建议您查看这篇文章
http://boredzo.org/pointers/
关于c - 指向数组的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31365923/