【问题标题】:Passing array pointer in C and Swiping Values from Different Arrays在 C 中传递数组指针并从不同数组中滑动值
【发布时间】:2018-03-24 14:20:07
【问题描述】:

这个应用程序应该使用下面的函数交换数组的前三个数字。当我交换像 1 2 3 4 5 这样的数字时,代码可以工作,但是当我尝试使用这个数字 5 3 4 9 8 7 2 时,它不会显示正确的输出。我真的找不到代码有什么问题。

#include <stdio.h>

int main(void){

    int a_lenth, i,a_content;
    printf("Enter the lenth of the array:");
    scanf("%d", &a_lenth);
    int arr[a_lenth];
    int arr2[a_lenth];

    for(i = 0; i < a_lenth; i++){
            printf("Enter the elements of the array:");
            scanf("%d", &a_content);
            arr[i] = a_content;
            arr2[i] = a_content;
    };

    roll(arr, a_content, arr2);

    return 0;
}

void roll(int *a1, int n, int *a2){
    int e;

    a2[0] = a1[2];
    a2[1] = a1[0];
    a2[2] = a1[1];


    for(e = 0; e < n; e++){
            printf("%d\n", a2[e]);
    }
}

【问题讨论】:

  • 这个调用roll(arr, a_content, arr2);中a_content是什么意思;
  • a_content 是从用户那里获取值并将其存储在数组 arr[0] = a_content 中的变量。
  • 如果一次还不足以理解我的问题,请再读一遍。
  • 如果我理解正确,n 应该是数组的长度。那为什么函数调用roll 是用a_content 完成的呢?不应该用a_lenth 完成吗?

标签: c arrays function pointers swap


【解决方案1】:

按照我的评论:

对函数 roll 的调用期望第二个参数是 int 数组的元素数,但您发送的参数是 a_content(我想这是一个小错误)

将其更改为:roll(arr, a_lenth, arr2);

输入:(问题中指定的那个)

Enter the lenth of the array:7
Enter the elements of the array:5
Enter the elements of the array:3
Enter the elements of the array:4
Enter the elements of the array:9
Enter the elements of the array:8
Enter the elements of the array:7
Enter the elements of the array:2

输出:

4
5
3
9
8
7
2

希望对你有帮助

【讨论】:

  • 谢谢,我不敢相信我犯了这么简单的错误。
【解决方案2】:

这将满足您的需求。正如在 roll 被错误调用之前指出的那样,因为 a_content 不是输出数组的长度。

int main(void){

    int a_length;
    int a_content;
    printf("Enter the lenth of the array:");
    scanf("%d", &a_length);
    int arr1[a_length];
    int arr2[a_length];

    for(int i = 0; i < a_length; i++){
        printf("Enter the elements of the array:");
        scanf("%d", &a_content);
        arr1[i] = a_content;
        arr2[i] = a_content;
    };

    //void roll(int *a1, int n, int *a2) where n == a_length
    arr2[0] = arr1[2];
    arr2[1] = arr1[0];
    arr2[2] = arr1[1];

    for(int e = 0; e < a_length; e++){
        printf("%d\n", arr2[e]);
    }

return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 2018-09-13
    • 2017-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多