C中包含错误值的数组

时间:2019-03-24 22:46:19

标签: c arrays pointers

该程序的目标是将数组的第一个元素和最后一个元素加在一起,并将该值设置为输出数组的第一个元素,然后照此继续向内移动。所有的总和将存储在输出数组中。对于该程序,规则规定,我只能使用指针和指针算术(即不使用下标,不使用“ []”等。)我已经使该程序适用于长度为2且长度为4的数组(因为我仅对偶数长度的数组实现了功能),但是当我尝试长度为6或以上的任何数组时,该程序会将不在第一个数组中的不正确的值加在一起。

我已经尝试使用两种不同的调试器来隔离问题的出处,并且我一生都无法解决。我花了几个小时查看有关C的说明,并遍历了代码,但是可以对它进行重做。我觉得数组和指针变量之间的交互方式似乎有问题,但是我不确定。我似乎找不到关于Stack Overflow的任何问题都与此相似(是的,我看过)。

if {[string compare $input1 $input2] <= 0} {
    ...
}

对于长度为2和4的数组(再次,我现在仅测试偶数),代码可以正常工作。

示例输出:

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);
        }
    }

}

现在这是要出问题的地方。

当我这样做时:

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

我最好的猜测是我使用指针或指针语法可能出了点问题。我能得到的任何帮助,无论是正面的还是负面的,将不胜感激。

这是main()函数:

1 + 0 = 1                                                                                                                        
2 + 3 = 5                                                                                                                        
3 + 4 = 7          

The output array is: 1 5 7  

1 个答案:

答案 0 :(得分:3)

您正在使用大小为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]);
    }
相关问题