我在下面的代码中通过Internet在数组中插入一个元素.我的问题是,如何在第一次插入时增加数组的大小,并在每次执行打印时打印垃圾.我也很渴望获取有关我得到的错误的详细信息.
代码是
#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]);
}
}
Run Code Online (Sandbox Code Playgroud)
输出是
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)
Run Code Online (Sandbox Code Playgroud)
谢谢你的时间.
您已声明了一个大小为5的数组LA.
int LA[] = {1,3,5,7,8};
Run Code Online (Sandbox Code Playgroud)
稍后,您的代码尝试添加其他元素,但是,LA的大小仍为5,因此您将值放在尚未分配的数组空间中.
然后有可能,数组正在堆栈上分配,并且由于您正在写入不属于数组的区域,因此您正在搞乱堆栈.
任何超出LA大小的printf访问索引都将发生在内存中的那个位置
| 归档时间: |
|
| 查看次数: |
7178 次 |
| 最近记录: |