【发布时间】:2017-11-16 22:26:07
【问题描述】:
我通过 Internet 获得了以下代码,用于在数组中插入一个元素。我的问题是“如何增加数组的大小,尤其是在第一次插入时,并且在每次执行打印 for 循环时都会打印垃圾?”。我也很想了解我遇到的错误的详细信息。
代码是
#include <stdio.h>
void main()
{
int k = 3, n = 5, i = 0, j = n;
int LA[] = {1,3,5,7,8};
printf("The original array elements are :\n");
for(i = 0; i<n; i++) {
printf("%d ",LA[i]);
}
n = n + 1;
while( j >= k){
LA[j+1] = LA[j];
j = j - 1;
}
LA[k] = 10;
printf("\nThe array elements after insertion1 :\n");
for(i = 0; i<n; i++) {
printf("%d ",LA[i]);
}
n = n + 1;
while( j >= k){
LA[j+1] = LA[j];
j = j - 1;
}
LA[k] = 20;
printf("\nThe array elements after insertion2 :\n");
for(i = 0; i<n; i++) {
printf("%d ",LA[i]);
}
n = n + 1;
while( j >= k){
LA[j+1] = LA[j];
j = j - 1;
}
LA[k] = 30;
printf("\nThe array elements after insertion3 :\n");
for(i = 0; i<n; i++) {
printf("%d ",LA[i]);
}
}
输出是
The original array elements are :
1 3 5 7 8
The array elements after insertion1 :
1 3 5 10 7 8
The array elements after insertion2 :
1 3 5 20 7 8 2087809280
The array elements after insertion3 :
*** stack smashing detected ***: ./a.out terminated
1 3 5 30 7 8 2087809280 -1077687568 Aborted (core dumped)
感谢您的宝贵时间。
【问题讨论】:
-
错误的详细信息是您损坏了堆栈。查找“为了乐趣和利润而粉碎堆栈”。 (免责声明:我还没有阅读代码)