c - 通过函数传递多个但不同的变量/输入?
问题描述
我想通过一个返回单个值/输出的函数传递多个不同的变量。我能想到的唯一方法是为需要通过它的每个值调用该函数。
例如。
int foo = 9;
int doo = 4;
int yoo = 23;
convertIntToSomethingElse(foo);
convertIntToSomethingElse(doo);
convertIntToSomethingElse(yoo);
我有一种强烈的感觉,这是一种糟糕的编程,并且有一种更有效的方法可以做到这一点。
解决方案
既然你问了一个例子。
有两种方法可以做到这一点:
首先,是将整个数组传递给一个函数,然后在数组中多次使用这些函数:
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]);
}
推荐阅读
- perl - 如何在 Perl Socket 模块中增加 sndbuf/rcvbuf 大小的套接字选项?
- java - 当 JAXBElement 值为 null 时,将 JAXB 注释的 PoJo 转换为 Json 时排除 null 属性
- winappdriver - WinAppDriver 不适用于侧面加载的通用应用程序
- vba - 设置框架语句中的类型不匹配
- sql-server - 重置 SSMS 的对象资源管理器详细信息的排序顺序
- python - 如何在 Pandas 数据框中命名列和索引?
- c# - datagrid customsorting BindingListCollectionView 输入 ListCollectionView 错误
- c++ - “ ans += (a[i] - ans * r > 0); ”是什么意思,其中 ans,r 是整数, a[i] 是数组元素?
- python - 当函数退出范围时,函数内部的 subprocess.Popen 调用是否会被垃圾收集?
- python - 在触发器中使用通配符时云功能部署失败