0

我有以下 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] 相同的指针。我真的不明白这怎么可能。代码有什么问题。为什么数组[4] = m[n][n]?

4

2 回答 2

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]);
}   
于 2013-02-11T00:33:43.683 回答
1

你的循环是错误的,数组C是从零开始的。意思是第一个元素是,a[0]最后一个元素是数组的大小。a[N-1]N

这:

for(i = 1; i <= n; i++)

应该是这样的:

for(i = 0; i < n; i++)

否则,您会超出数组边界。

作为旁注,您正在使用 VLA 但未指定C99标签。确保你知道你在做什么。

于 2013-02-11T00:34:04.673 回答