简体   繁体   English

在 C99 中的函数之间共享变量

[英]Share variables between functions in C99

  1. Taking in input from the main matrix_1 , I need to create a new one and print it with only the odd numbers.从主matrix_1输入,我需要创建一个新的并仅用奇数打印它。 Now I'm printing it from the function, but I need to print it from the main() ;现在我从函数打印它,但我需要从main()打印它; how can I do that?我怎样才能做到这一点?
#include <stdio.h>
#define len 4

void copiaDispari();

int main () {

    int i, j, matrix_1[len][len];

    for (i=0; i < len; i++){
        for (j=0; j < len; j++) {
            printf ("Inserisci il numero della matrice %d %d:", i, j);
            scanf ("%d", &matrix_1[i][j]);
        }
    }

    copiaDispari(matrix_1);

    for (i=0; i < len; i++){
        for (j=0; j < len; j++) {
            printf ("%d", matrix_2[i][j]);
        }
        printf("\n");
    }

    return 0;
}

void copiaDispari(int matrix_1[len][len]) {

    int matrix_2[len][len]= {{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0}}, i, j, l=0, m=0;


    for (i=0; i < len; i++){
        for (j=0; j < len; j++){
            if (matrix_1[i][j]%2!=0){
                if (l==4) {
                    l=0; m++;
                }
                matrix_2[m][l] = matrix_1[i][j];
                l++;
            }
        }
    }

    for (i=0; i < len; i++){
        for (j=0; j < len; j++) {
            printf ("%d", matrix_2[i][j]);
        }
        printf("\n");
    }

    return;
}
  1. Imagine I have to pass 5 or 6 variables from a function void yeah() to another function void yessss() ;想象我必须从一个功能通过5个或6个变量void yeah()到另一个功能void yessss() ; how can I achieve it?我怎样才能实现它?
  2. When should I use a void function, and when an int function?什么时候应该使用 void 函数,什么时候使用 int 函数?
  1. The simplest approach is to allocate the second array in main() and pass it as an argument to the function (as well as the first array).最简单的方法是在main()分配第二个数组并将其作为参数传递给函数(以及第一个数组)。

     int i, j, matrix_1[len][len], matrix_2[len][len] = { { 0 } }; … copiaDispari(matrix_1, matrix_2); … void copiaDispari(int matrix_1[len][len], matrix_2[len][len]) { … }

    Other techniques use dynamic memory management ( malloc() et al), or encapsulate the array in a structure and pass the structure type around (you can return structures that contain arrays; you can't return arrays from functions), or (sometimes, but not often) using a static array in the function and returning a pointer to it (don't do this), or using a global variable (don't do this, either!).其他技术使用动态内存管理( malloc()等),或将数组封装在结构中并传递结构类型(您可以返回包含数组的结构;您不能从函数中返回数组),或者(有时,但不经常)在函数中使用static数组并返回指向它的指针(不要这样做),或使用全局变量(也不要这样做!)。

  2. Functions can have semi-indefinitely large numbers of parameters.函数可以有半无限大的参数。 C11 §5.2.4.1 Translation limits requires the compiler to accept function definitions and calls with at least 127 arguments. C11 §5.2.4.1 翻译限制要求编译器接受至少具有 127 个参数的函数定义和调用。 A mere 5 or 6 doesn't cause a compiler any angst.仅仅 5 或 6 不会引起编译器任何焦虑。 However, reducing the number of arguments is a good idea.但是,减少参数的数量是个好主意。

    If you want to return multiple values from a function, you can pass multiple pointers to the function and have it modify the variables via the pointers.如果要从函数返回多个值,可以将多个指针传递给函数,并让它通过指针修改变量。 Or you can wrap the set of variables into a structure and pass a pointer to a suitable structure, or you can return a suitable structure to the calling function.或者您可以将变量集包装到一个结构中并传递一个指向合适结构的指针,或者您可以将合适的结构返回给调用函数。

  3. When the function produces a value that will be used by the calling code, you should often not use a void function.当函数产生一个将被调用代码使用的值时,通常不应使用void函数。 You can pass pointers to variables and the function might modify those to return its answer.您可以传递指向变量的指针,函数可能会修改这些指针以返回其答案。 If the function can fail, you might have it return 0 on success and some other value on failure;如果函数可能失败,你可能让它在成功时返回 0,在失败时返回一些其他值; that precludes it having the return type void , of course.当然,这排除了它具有返回类型void Error handling is a major part of C programming.错误处理是 C 编程的主要部分。 If a function doesn't return a value to indicate success or failure, it can be hard to know whether there a problems.如果函数没有返回值来指示成功或失败,则很难知道是否存在问题。


Incidentally, the forward declaration of the function should not be:顺便说一句,函数的前向声明不应该是:

void copiaDispari();

In your original code, it should be:在您的原始代码中,它应该是:

void copiaDispari(int m1[len][len]);

In the revised code, it should be;在修改后的代码中,应该是;

void copiaDispari(int m1[len][len], int m2[len][len]);

This will help prevent mistakes such as calling the function with the wrong number of arguments.这将有助于防止错误,例如使用错误数量的参数调用函数。

You should never write a function declaration with () for the argument list.您永远不应该为参数列表编写带有()的函数声明。 That says the function takes an indeterminate number of arguments (but it isn't a variable argument list function like printf() ).这表示该函数采用不确定数量的参数(但它不是像printf()那样的可变参数列表函数)。 If the function takes no arguments, write int function(void);如果函数没有参数,写int function(void); in the declaration, and for consistency, int function(void) { … } in the definition.在声明中,为了一致性,在定义中使用int function(void) { … } Although you can write int function() { … } in the definition, this does not provide a prototype for the function and it can be miscalled in the same source file.尽管您可以在定义中编写int function() { … } ,但这不提供该函数的原型,并且可能在同一源文件中被错误调用。 Note that C++ differs from C in this area.请注意,C++ 在这方面与 C 不同。 Old C code (from before the C89/C90 standard was produced) uses the () notation;旧的 C 代码(在 C89/C90 标准产生之前)使用()表示法; it didn't have a choice.它没有选择。 Code written in this millennium should not use the () notation.在这个千年编写的代码不应该使用()符号。

  1. [rephrased] how to send data back to the calling function? [改写] 如何将数据发送回调用函数?

Basically you have two options基本上你有两个选择

create the object to hold the data in the calling function, pass a pointer and have the called function use that创建对象以在调用函数中保存数据,传递一个指针并让被调用函数使用该对象

int main(void) {
    int src1[10][10] = {0};
    int src2[10][10] = {0};
    fx(src1, src2);
}

or use malloc() (and friends) in the called function then return that to the caller which will be responsible to free the resources.或者在被调用的函数中使用malloc() (和朋友),然后将其返回给负责free资源的调用者。

typedef int m2[10][10];

int main(void) {
    int src[10][10] = {0};
    m2 *dst = fx(src);
    // use dst
    free(dst);
}

m2 *fx(int m[10][10]) {
    m2 *x = malloc(10 * 10 * sizeof (int));
    // work with m to change x values
    return x;
}

A third option, to be frowned upon (no example code), is to use global variables.不赞成的第三种选择(没有示例代码)是使用全局变量。

  1. how to pass 5 or 6 variables between functions?如何在函数之间传递 5 或 6 个变量?

Basically, just specify them in the calling code, like基本上,只需在调用代码中指定它们,例如

printf("%s bought %d %s for %.2f\n", name, quantity, "apples", quantity * price);

Or, if the variables are related, you can try grouping them in a struct and pass a pointer或者,如果变量是相关的,您可以尝试将它们分组在一个struct并传递一个指针

struct GroupData {
    char name[100];
    int quantity;
    char item[100];
    double price;
};
struct GroupData x = {"John", 42, "apple", 0.31};
workwithdata(&x); // can also pass a copy of the struct
                  // workwithcopy(x);
  1. when to use void function or int function?什么时候使用 void 函数或 int 函数?

use void when there is no need to use a value from the function当不需要使用函数中的值时使用void

void beep(void); // sounds the bell

use int when you want to use a value from the function当您想使用函数中的值时使用int

int currenttemp(void); // returns the temperature

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

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