c - C 中的数组包含不正确的值
问题描述
该程序的目标是将数组的第一个和最后一个元素相加,并将该值设置为输出数组的第一个元素,然后继续向内移动。所有的和将存储在一个输出数组中。对于这个程序,规则规定我只能使用指针和指针运算(即没有下标,没有 '[]' 等)。我已经让程序也适用于长度为 2 和长度为 4 的数组(因为我仅实现了偶数长度数组的功能)但是,当我尝试任何长度为 6 或以上的数组时,程序会将不在第一个数组中的错误值加在一起。
我已经尝试过使用两个不同的调试器来隔离问题的来源,而对于我的生活,我无法弄清楚。我花了几个小时查看我关于 C 的笔记并浏览代码,尽我所能对其进行修改。我觉得数组和指针变量之间的交互方式好像有问题,但我不确定。我似乎在 Stack Overflow 上找不到任何与这个太相似的问题(是的,我看过)。
void add(int *a1, int array_size, int *a2) {
int * p;
int * temp = (a1+(array_size-1));
if (array_size % 2 == 0) {
array_size = array_size/2;
for (p = a2; p < (a2+array_size); p++) {
*p = *a1 + *temp;
printf("%d", *a1);
printf(" + %d", *temp);
a1++;
temp--;
printf(" = %d\n", *p);
}
}
}
对于长度为 2 和 4 的数组(同样,我现在只测试偶数),代码工作正常。
示例输出:
Enter the length of the array: 2
Enter the elements of the array: 1 2
1 + 2 = 3
The output array is: 3
Enter the length of the array: 4
Enter the elements of the array: 1 2 3 4
1 + 4 = 5
2 + 3 = 5
The output array is: 5 5
现在这是出错的地方。
当我这样做时:
Enter the length of the array: 6
Enter the elements of the array: 1 2 3 4 5 6
我预计:
1 + 6 = 7
2 + 5 = 7
3 + 4 = 7
The output array is: 7 7 7
但相反,输出是:
1 + 0 = 1
2 + 3 = 5
3 + 4 = 7
The output array is: 1 5 7
我最好的猜测是我使用指针或指针语法出现了问题。我能得到的任何帮助,无论是积极的还是消极的,都将不胜感激。
这是 main() 函数:
int main() {
int size = 0;
int out_size = 0;
int arr[size];
printf("Enter the length of the array: ");
scanf("%d", & size);
printf("\nEnter the elements of the array: ");
for (int i = 0; i < size; i++) {
scanf("%d", & arr[i]);
}
if (size % 2 == 0) {
out_size = size/2;
}
else{
out_size = ((size-1)/2) + 1;
}
int out[out_size];
//calling the add function and using the addresses of arrays + array size
add(arr, size, out);
//iterating through and printing output array which has now been
//altered by the move function
printf("\nThe output array is: ");
for (int i = 0; i < out_size; i++) {
printf("%d ", out[i]);
}
return 0;
}
解决方案
您正在使用大小为 0 的数组:
int main() {
int size = 0;
int out_size = 0;
int arr[size]; // <- Here is your problem
您可以在阅读后移动数组声明size
:
int main() {
int size = 0;
int out_size = 0;
printf("Enter the length of the array: ");
scanf("%d", & size);
int arr[size];
printf("\nEnter the elements of the array: ");
for (int i = 0; i < size; i++) {
scanf("%d", & arr[i]);
}