[英]Stack smashing error when manipulating array of ints in function
So I'm trying to make a simple program that takes an array that is partially full and adds an integer to the beginning shifting all existing elements to the right. 因此,我试图制作一个简单的程序,该程序采用部分填充的数组,并在开头添加一个整数,以将所有现有元素向右移动。 It seems what I have here adds and shifts things properly but once all the code executes, I get a stack smashing detected error. 看来我在这里所添加的内容正确地进行了移位,但是一旦所有代码执行完毕,我就会得到堆栈粉碎检测到的错误。
Here is my code: 这是我的代码:
#include <stdio.h>
void addCommand(int *, int, int);
void main() {
int i;
int list[10];
list[0] = 1;
list[1] = 5;
printf("Before add:\n");
for (i = 0; i < 2; i++) {
printf("%d\n", list[i]);
}
addCommand(list, sizeof(list), 4);
printf("Adding 4:\n");
for (i = 0; i < 3; i++) {
printf("%d\n", list[i]);
}
}
void addCommand(int *arr, int size, int new) {
int k;
printf("%d", arr[0]);
for (k = size - 1; k >= 0; k--) {
if (&arr[k] != NULL) {
if (k > 0) {
arr[k] = arr[k-1];
} else {
arr[k] = new;
}
}
}
}
And here's the output: 这是输出:
If anyone could point out what I'm doing wrong here, it would be much appreciated! 如果有人指出我在这里做错了,将不胜感激!
addCommand(list, sizeof(list), 4);
above line doesn't pass number of element in list array. 上一行未通过列表数组中元素的数量。 you have to do something like this: 您必须执行以下操作:
sizeof(arr)/sizeof(arr[0])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.