gpt4 book ai didi

c - GCC 新手 - 运行数组插入会在本地提供与在线编译器不同的输出

转载 作者:行者123 更新时间:2023-11-30 20:16:54 25 4
gpt4 key购买 nike

我正在研究 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];
}

关于c - GCC 新手 - 运行数组插入会在本地提供与在线编译器不同的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59400902/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com