C语言 GCC 的新手 - 在本地运行数组插入给我的输出与在线编译器不同



我正在通过TuturialsPoint算法并尝试使用GCC运行C代码。有谁知道为什么我的本地输出与在线 C 编译器生成的输出不同?

#include <stdio.h>
main()
{
int LA[] = {1, 3, 5, 7, 8};
int item = 10, k = 3, n = 5;
int i = 0, j = n;
printf("The original array elements are :n");
for (i = 0; i < n; i++)
{
printf("LA[%d] = %d n", i, LA[i]);
}
n = n + 1;
while (j >= k)
{
LA[j + 1] = LA[j];
j = j - 1;
}
LA[k] = item;
printf("The array elements after insertion :n");
for (i = 0; i < n; i++)
{
printf("LA[%d] = %d n", i, LA[i]);
}
}

预期输出(来自在线 gcc 编译器(

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

我的本地输出:

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

我正在使用 gcc 版本 8.2.0(MinGW.org GCC-8.2.0-5(

您定义了一个正好包含 5 个元素的数组。

int LA[] = {1, 3, 5, 7, 8};

因此,访问数组元素的有效索引范围为[0, 5)

此数组可能不会放大。因此,使用等于或大于 5 的索引会导致访问和覆盖数组之外的内存。

您最初需要定义数组,其中包含允许在 5 个显式初始化元素之外插入新元素的元素数。

你的意思是像下面这样

#include <stdio.h>
int main(void) 
{
enum { N = 10 };
int a[N] = { 1, 3, 5, 7, 8 };
size_t n = 0;
while ( a[n] != 0 ) ++n;
printf( "The original array elements are :" );
for ( size_t i = 0; i < n; i++ ) printf( "%d ", a[i] );
putchar( 'n' );
int item = 10;
size_t pos = 3;
size_t j = n;
if ( pos < j )
{
for ( ; j != pos; j-- )
{
a[j] = a[j-1];
}
}
a[j] = item;
++n;
printf( "The array elements after insertion : " );
for ( size_t i = 0; i < n; i++ ) printf( "%d ", a[i] );
putchar( 'n' );
return 0;
}

程序输出为

The original array elements are :1 3 5 7 8 
The array elements after insertion : 1 3 5 10 7 8 

注意:此代码片段

if ( pos < j )
{
for ( ; j != pos; j-- )
{
a[j] = a[j-1];
}
}

可以替代此循环

for ( ; pos < j; j-- )
{
a[j] = a[j-1];
}

最新更新