C 为什么两个变量共享相同的地址?
在iMac、OsX 10.5上使用gcc版本4.0.1 某些变量被分配了相同的地址 作为二维数组中的第二组元素 我应该做什么来防止编译器以这种方式分配地址 包括一个演示问题的程序:C 为什么两个变量共享相同的地址?,c,variables,gcc,overlap,memory-address,C,Variables,Gcc,Overlap,Memory Address,在iMac、OsX 10.5上使用gcc版本4.0.1 某些变量被分配了相同的地址 作为二维数组中的第二组元素 我应该做什么来防止编译器以这种方式分配地址 包括一个演示问题的程序: #include <stdio.h> long a[1][10]; long b; long c; int main() { printf( "Address of a[0][0]: %p\n", &a[0][0] ); printf( "Address of a[0][1]:
#include <stdio.h>
long a[1][10];
long b;
long c;
int main()
{
printf( "Address of a[0][0]: %p\n", &a[0][0] );
printf( "Address of a[0][1]: %p\n\n", &a[0][1] );
printf( "Address of a[1][0]: %p\n", &a[1][0] );
printf( "Address of a[1][1]: %p\n\n", &a[1][1] );
printf( "Address of b: %p\n", &b );
printf( "Address of c: %p\n\n", &c );
}
如果需要,我对gcc输出有一个“详细”的描述。因为您将数组定义为长[1][10]。这意味着您只能访问[0][N]
请记住,当您定义数组的大小时,您最多可以索引N-1。您正在打印不存在的内容的地址 [1][0]的printf地址:%p\n,&a[1][0] 由于您声明的a与[1][10];;一样长;,没有&a[1][0],这是超出数组维度的值。只有[0][0到9]存在。长[1][10]将在堆栈上为10个长值保留空间。 a将指向第一个元素。 长b将为一个长值保留空间,长c也会。 b将直接位于a之后,c将直接位于b之后 [1][0]将指向位于a的第一个元素之后的长值大小的10倍1的元素。这是b a[1][1]将指向位于a的第一个元素后面的长值大小的10倍1加1倍的元素。在这种情况下,这将是c 这就是你遵守相同地址的原因。nos,&Steffen 谢谢你及时的回复…我看到了我现在明显的错误 我学会了使用Qbasic编程,其中
DIM a(1,10) AS INTEGER 'the subscripts give the maximum array value...
'and not the number of elements in the array.
…是一个2*11阵列
我和我都在痛苦地试图“转换”到C
William。简单地说,该代码正在访问绑定项的垃圾,垃圾值可以是任何东西。@SyedMauzeRehan它不是在访问它们,而是通过计算超出边界的指针来调用UB。
DIM a(1,10) AS INTEGER 'the subscripts give the maximum array value...
'and not the number of elements in the array.