我有以下C代码:
int main(int argc, char *argv[])
{
int n = argc - 1;
int array[n];
int m[n][n];
int i = 0;
for(i = 1; i<=n;i++)
{
array[i] = atoi(argv[i]);
printf("%d\n",array[i]);
}
printf("array[4] = %d\n",array[4]);
for(i = 1; i<=n;i++)
{
m[i][i] = 0;
printf("address of m[i][i] = %p\n",&m[i][i]);
}
printf("value of array[4] =%d pointer = %p\n",array[4],&array[4]);
for(i=1;i<=n;i++) printf("After %d\n",array[i]);
return 0;
}
如果我使用以下命令运行:“./ program 30 35 15 5 10 20 15”输出为:
30
35
15
5
10
20
25
array[4] = 5
address of m[i][i] = 0xbf93070c
address of m[i][i] = 0xbf93072c
address of m[i][i] = 0xbf93074c
address of m[i][i] = 0xbf93076c
address of m[i][i] = 0xbf93078c
address of m[i][i] = 0xbf9307ac
address of m[i][i] = 0xbf9307cc
value of array[4] =0 pointer = 0xbf9307cc
After 30
After 35
After 15
After 0
After 10
After 20
After 25
注意array [4]如何与m [n] [n]具有相同的指针。我真的不明白这是怎么回事。代码有什么问题。为什么array [4] = m [n] [n]?
答案 0 :(得分:1)
for(i = 1; i<=n;i++)
{
m[i][i] = 0;
printf("address of m[i][i] = %p\n",&m[i][i]);
}
您已覆盖未为m保留的空间;
我应该从0到n-1
for(i = 0 ; i < n ; i++)
{
m[i][i] = 0;
printf("address of m[i][i] = %p\n",&m[i][i]);
}
答案 1 :(得分:1)
您的循环错误,C
中的数组从零开始。这意味着第一个元素是a[0]
,最后一个元素是a[N-1]
,其中N
是数组的大小。
此:
for(i = 1; i <= n; i++)
应该是这样的:
for(i = 0; i < n; i++)
否则你会超越数组边界。
作为旁注,您使用的是VLA但未指定C99
标记。确保你知道自己在做什么。