首页 > 解决方案 > 通过函数传递多个但不同的变量/输入?

问题描述

我想通过一个返回单个值/输出的函数传递多个不同的变量。我能想到的唯一方法是为需要通过它的每个值调用该函数。

例如。

int foo = 9;
int doo = 4;
int yoo = 23;
convertIntToSomethingElse(foo);
convertIntToSomethingElse(doo);
convertIntToSomethingElse(yoo);

我有一种强烈的感觉,这是一种糟糕的编程,并且有一种更有效的方法可以做到这一点。

标签: cfunction

解决方案


既然你问了一个例子。

有两种方法可以做到这一点:

首先,是将整个数组传递给一个函数,然后在数组中多次使用这些函数:

int yourArray[3] = {9, 4, 23};
//get the number of elements in the array by dividing total size by a 
//size of a single element
//if you know the size you can just use that, but it's not reccomended

size_t n = sizeof(a)/sizeof(a[0]); //Pass this to function to get array size

void yourFunction (int a[], int sizeOfArray){

    int i;
    for(i=0;i<sizeOfArray;i++){
        //do stuff you need
    }
}

第二种方法是使用循环在数组中多次运行该函数:

for(i=0; i<n; i++){
    yourFunction(yourArray[i]);
}

推荐阅读