我刚刚在“C编程语言”一书中读到,数组不是变量,并且看到数组到指针的分配(反之亦然)不能作为结果。那么如果数组不是变量那么它是什么?
答案 0 :(得分:3)
Array是一个包含许多值的数据结构,所有值都具有相同的类型,并且数组名称是不可修改的 l值(命名的内存位置) - 可以寻址,但不可修改。这意味着它不能被修改或不能成为赋值运算符的左操作数。
int a[10] = {0};
int *p = a; //OK
a++ // Wrong
a = p; // Wrong
答案 1 :(得分:3)
int numbers[] = {1,2,3}
numbers
不是变量,它是数组名称,它只是数组中第一个元素的地址。要验证这一点,请执行以下操作,查看numbers
的地址和numbers[0]
的地址:printf("%p and %p and %p", &numbers, numbers, &numbers[0]);
所有三个指针都具有相同的值,因为numbers
是什么都没有但是数组中第一个元素的地址。因此numbers
不是包含指针或值的变量,因为它在内存中没有专用地址来存储值。
但是,请查看此指针变量:
int *pnumbers = numbers;
`printf("%p and %p and %p", &pnumbers, pnumbers, &pnumbers[0]);`
您会注意到&pnumbers
在内存中有不同的地址,因为pnumber
在内存中有一个专用地址,用于存储数组中第一个元素的地址numbers
。
将所有代码放在一起:
#include <stdio.h>
main(){
int numbers[] = {1,2,3};
printf("%p and %p and %p\n", &numbers, numbers, &numbers[0]); // Address of numbers, value of numbers, first element of numbers
int *pnumbers = numbers;
printf("%p and %p and %p\n", &pnumbers, pnumbers, &pnumbers[0]); // Address of pnumbers, value of pnumbers, first element of the array pnumbers is pointing to
}
<强>输出强>
0xbfb99fe4 and 0xbfb99fe4 and 0xbfb99fe4 // All three have the same address which is the address of the first element in the array
0xbfb99fe0 and 0xbfb99fe4 and 0xbfb99fe4 // The first one is different since pnumbers has been allocated a memory address to store a pointer which is the first element of the array numbers
答案 2 :(得分:1)
这是一个占位符。用于表示引用存储器的顺序部分的常用方法的符号。它本身并不是变量。
int main(int argc, char** argv)
{
int array[10];
int value'
int* pointer;
value = array[0]; // Just fine, value and array[0] are variables
array[0] = value; // Just fine, value and array[0] are variables
pointer = &array[0]; // Just fine, &array[0] is an address
pointer = array; // Also just fine
//Because the compiler treats "array" all by itself as the address of array[0]
//That is: array == &array[0]
&array[0] = pointer // ERROR, you can't assign the address of something to something else.
array = pointer; // ERROR, array is not a variable, and cannot be assigned a value.
//Also bad, but technically they compile and could theoretically have their use
pointer = value;
pointer = array[0];
array[0] = pointer;
//Intermixing pointers and non-pointer variables is generally a bad idea.
}
array
通常被视为变量,因为它表示该内存块的(第一项)的地址。但这不是变数。它没有自己的内存来存储任何东西。人们将指针设置为“数组”,因为它是一个方便的约定,编译器知道这意味着什么,而且它很常见。
答案 3 :(得分:0)
数组是相同类型的元素序列。如果指定一个指向数组的指针,指针将指向数组中第一个变量的地址。
int a[10];
int *p;
int *p2;
p = a;
p2 = &a[0];
printf("%d\n", p == p2);
输出:
1
答案 4 :(得分:0)
I've just read in the book "The C Programming Language" that array is not a
variable and saw that assignment of array to pointers (and vice versa)
允许反之亦然...数组就像一个常量指针(你不能改变它指向的地址)。但是,您可以将该地址分配给指针。
#include <stdio.h>
int main()
{
int x[3] = {1, 2, 3};
int *p = x;
p[0] = 50;
printf("%d", x[0]);
}