局部变量正在修改不相关变量的值

时间:2018-10-24 23:02:56

标签: c memory overflow

我一直在用一些代码将成员添加到一个数组中,当我尝试对代码进行一些更改时,我意识到预期的输出不正确(修改后的数组未显示)。调试时,我看到将int i声明为全局变量,而不是在for循环中声明了预期的输出。

但是,我发现问题与变量n有关,原因是变量while (j >= k)被声明为for循环的初始化时在int i内部进行了修改;但我不知道为什么会这样。如果有人可以帮助我了解发生的原因和原因,我将非常感激

这是我的代码,可以完成预期的输出:

#include <stdio.h>

int main() {
    int LA[] = {1,3,5,7,8};
    int item = 10, k = 3, n = sizeof(LA)/sizeof(LA[0]);
    int j = n;
    int i;

    printf("n  = %d\n",n);
    printf("The original array elements are :\n");

    for(i = 0; i<n; i++) {
        printf("LA[%d] = %d \n", i, LA[i]);
    }
    printf("n  = %d\n",n);
    n = n + 1;
    printf("n  = %d\n",n);
    while( j >= k) {
        LA[j+1] = LA[j];
        j = j - 1;
    }
    printf("n  = %d\n",n);
    LA[k] = item;

    printf("The array elements after insertion :\n");
    printf("n = %d\n",n);
    for(i = 0; i<n; i++) {
        printf("LA[%d] = %d \n", i, LA[i]);
    }
}

这是我的预期输出:

n  = 5
The original array elements are :
LA[0] = 1
LA[1] = 3
LA[2] = 5
LA[3] = 7
LA[4] = 8
n  = 5
n  = 6
n  = 6
The array elements after insertion :
n = 6
LA[0] = 1
LA[1] = 3
LA[2] = 5
LA[3] = 10
LA[4] = 7
LA[5] = 8

这是我的代码,它没有预期的输出:

#include <stdio.h>

int main() {
    int LA[] = {1,3,5,7,8};
    int item = 10, k = 3, n = sizeof(LA)/sizeof(LA[0]);
    int j = n;

    printf("n  = %d\n",n);
    printf("The original array elements are :\n");

    for(int i = 0; i<n; i++) {
        printf("LA[%d] = %d \n", i, LA[i]);
    }
    printf("n  = %d\n",n);
    n = n + 1;
    printf("n  = %d\n",n);
    while( j >= k) {
        LA[j+1] = LA[j];
        j = j - 1;
    }
    printf("n  = %d\n",n);
    LA[k] = item;

    printf("The array elements after insertion :\n");
    printf("n = %d\n",n);
    for(int i = 0; i<n; i++) {
        printf("LA[%d] = %d \n", i, LA[i]);
    }
}

这是我的意外输出:

n  = 5
The original array elements are :
LA[0] = 1
LA[1] = 3
LA[2] = 5
LA[3] = 7
LA[4] = 8
n  = 5
n  = 6
n  = 0
The array elements after insertion :
n = 0

为什么要根据n的声明修改变量int i

0 个答案:

没有答案