简体   繁体   English

(C)调用函数时,将多个值存储在数组中

[英](C) When calling function, store multiple values in array

So, when calling a function I wish to put two values in, then those two values to be saved in an array in the function argument. 因此,在调用函数时,我希望输入两个值,然后将这两个值保存在函数参数的数组中。

ie

function(1,2); (calling the function)

void function(int x[2]); (declaration of function)

with x[0] and x[1] being the two arguments when calling the function (ie the 1 and 2). 其中x [0]和x [1]是调用函数时的两个参数(即1和2)。

Any help would be appreciated. 任何帮助,将不胜感激。

You can use compound literals if you have two array members, but no array, and wish to call such a function: 如果您有两个数组成员,但没有数组,并且希望调用这样的函数,则可以使用复合文字:

void function(int x[2]);     // declaration of function

function((int [2]) {1, 2});  // calling the function

You can also use variables within the compound literal. 您也可以在复合文字中使用变量。 Here is a simple example program: 这是一个简单的示例程序:

#include <stdio.h>

void function(int x[2]);

int main(void)
{
    int arg1 = 3;
    int arg2 = 4;

    puts("Calling function with constants in compound literal:");
    function((int [2]) {1, 2});

    puts("Calling function with variables in compound literal:");
    function((int [2]) {arg1, arg2});

    return 0;
}

void function(int x[2])
{
    printf("x[0] = %d, x[1] = %d\n", x[0], x[1]);
}

Program output: 程序输出:

Calling function with constants in compound literal:
x[0] = 1, x[1] = 2
Calling function with variables in compound literal:
x[0] = 3, x[1] = 4

If you want to call a function that expects an array of two, passing 2 separate values is not the same thing. 如果要调用需要两个数组的函数,则传递2个单独的值不是同一回事。

This is as close as I can get: 这是我所能接近的:

void function(int x[2]) {....}

void caller(int a, int b)
{
    int args[2] = {a, b};  /* Convert two args into an array */
    function(args);        /* Call the function with an array */
}

int main(void)
{
    caller(1, 2);
}

Maybe Variable-length argument is what you want : 也许可变长度参数是您想要的:

void function(int i, ...) { 
    int tmp; 
    va_list num_list; 

    va_start(num_list, i); 

    for(int j = 0; j < i; j++) 
        cout << va_arg(num_list, int) << endl; 

    va_end(num_list); 
}

the first 'i' is tell the function how much argument you input. 第一个“ i”是告诉函数您输入了多少参数。 using this like: 像这样使用:

function(2,3,4); // pass 2 argument, 3 and 4

function(1,2); 函数(1,2); the function call will look for definition of type (int , int). 函数调用将查找类型的定义(int,int)。

void function(int x[2]); 无效函数(int x [2]); this function argument is of an array type. 此函数参数为数组类型。 so it is not possible to call the function by function(1,2); 因此不可能通过function(1,2)来调用该函数;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM