为什么指针可以分配的值? [英] why a pointer can be assigned value?
问题描述
我有一个难题在这里:
int *a=*b;
a[1]=3;
a[2]=5
a是一个指针数组,并赋值为b。在我的理解中,[]应该是一个地址,所以为什么在实践中,我们可以将指针(在这种情况下,[])分配价值的地方?任何解释?
a is a pointer array and is assigned value as b. In my understanding, a[]should be a address, so why in practice we can assign value to the place the pointer (in this case a[]) to? Any explain?
推荐答案
我假设这是C或客观的C / C ++的C子集,因为C +,Java,PHP和以及其他类似C语言的唐'T使用指针。
I'm assuming this is C, or the C subset of Objective C/C++, since C+, Java, PHP, and the other C-like languages don't use pointers.
使用code标记和每行一个语句。
Use code tags and a single statement per line.
语句
int *a = *b;
创建为指针为int。不是一个指针的指针为int,指针为int。
Creates a as a pointer to int. Not a pointer to pointer to int, a pointer to an int.
然后,它会将当前地址,一个是B的间接引用,不管b为。你没有表现出b的声明。除非b为类型 INT **
,你应该得到一个编译器警告。
It then sets the current address in a to be a dereference of b, whatever b is. You did not show the declaration of b. Unless b is of type int **
, you should be getting a compiler warning.
一个不是指针数组。一个是指向一个int。它可以指向单一int或它可以作出指向整数的数组。编译器不能看出其中的差别。
a is not a pointer array. a is a pointer to an int. It could point to a single int, or it could be made to point to an array of ints. The compiler can't tell the difference..
如果b为类型 INT **
,或指针指向int的指针,那么你的声明取消引用这些指针之一,并提出了指向第一子阵列内湾
If b is of type int **
, or pointer to pointer to int, then your statement dereferences one of those pointers and makes a point to the first sub-array inside b.
在code
a[1] = 3;
假设一个是指向整数数组,因为编译器不能做任何范围检查,它试图索引数组和值保存到第二int类型的内存块,一个点至。如果没有指向的内存足够大,可以容纳至少2的整数块,这份声明可能使用受保护的内存现代计算机上崩溃,它也可能只是覆盖以下的内存。
assumes that a is a pointer to an array of integers, and since the compiler can't do any range checking, it tries to index into the array and save a value to the second int in the block of memory that a points to. If a does not point to a block of memory large enough to contain at least 2 integers, this statement may crash on a modern computer using protected memory, it might also just overwrite the memory that follows.
正如@EdS。在下面评论指出,这是在业务被称为
As @EdS. points out in a comment below, this is known in the business as
未定义行为
如果你打算使用C指针这样的,责任在你,以确保它真正指向有效的内存,如果你要使用一个指针,如果它是一个数组,你责任在你确保你不超过内存的边界由指针指向。
If you're going to use a C pointer like this, the burden is on you to make sure that it really points to valid memory, and if you're going to use a pointer as if it's an array, you the burden is on you to make sure that you don't exceed the bounds of the memory pointed to by the pointer.
这篇关于为什么指针可以分配的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!