c - 正在研究如何使用函数调用数组来打印所述数组?

标签 c

我正在尝试从函数调用数组并打印出数组中的 5 个数字。

 #include <stdio.h>
    int i;
    int n;

    void printArray(int n, int i);

    int main(void){
        int n[5]={42, 30, 45, 3, 49};

        printf("%s%13s\n", "Element", "Value");

        printArray(int n,int i);
    }

    void printArray(int n, int i){

    for(i =0; i<5; ++i){

        printf("%7u%13d\n",i,n[i]);
    }

最佳答案

试试这个

    #include <stdio.h>

    // int i;  Don't use global variables
    // int n;  

    void printArray(int n[], int num_to_print);  // Tell n is array using []

    int main(void){
        int n[5]={42, 30, 45, 3, 49};

        printf("%s%13s\n", "Element", "Value");

        printArray(n, 5);   // Don't use any types when calling the function
    }

    void printArray(int n[], int num_to_print){     // Tell n is array using []

        for(int i=0; i<num_to_print; ++i){

            printf("%7d%13d\n", i, n[i]);
        }
    }

如果您总是想打印恰好 5 个元素,您可以这样做:

    #include <stdio.h>

    void printArray(int n[]);

    int main(void){
        int n[5]={42, 30, 45, 3, 49};

        printf("%s%13s\n", "Element", "Value");

        printArray(n);
    }

    void printArray(int n[]){

        for(int i=0; i<5; ++i){

            printf("%7d%13d\n", i, n[i]);
        }
    }

关于c - 正在研究如何使用函数调用数组来打印所述数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53377243/

相关文章:

c++ - _read 函数返回文件句柄的过时值

c - 我的 Lcov 命令无法写入目录?

c - 如何在不知道长度的情况下初始化 C 中的字符串,并继续向其附加字符?

c - 当我给 scanf() 一个非数字作为输入时,如何继续循环?

C中for结构头表达式值的计算

c - 为什么SX1272的每个SPI寄存器与0x80进行或操作

C- 将 realloc 与字符串指针合并

C 通用宏名称 - gcc -fextended-identifiers

使用 XCode 编译 C 程序

c - 如何直接操作输出流? (是 : why it's not increment value of increment operator in case of assignment in c? )