简体   繁体   English

用C编写函数,传递参数

[英]Writing functions in C, passing arguments

I found a code and I want to use it. 我找到了一个代码,我想使用它。 When I run it from a terminal by ./code 20181010 0810, it works perfectly. 当我从终端通过./code 20181010 0810运行它时,它可以完美运行。 I was trying to rewrite this code into function. 我试图将这段代码重写为函数。 The main code was declared by 主要代码由

int main (int argc, char *inp[]) { //some calculations }

So, I changed it into: 因此,我将其更改为:

int calc(int argc, char *inp[]) { //some calculations }

and the write main code with additional calculations: 并编写带有其他计算的主代码:

int calc(int argc, char *inp[]);
int main(int argc, char *inp[]) {

    char* c_date;
    char* c_hour;
    time_t timer;
    char buffer1[26], buffer2[26];
    struct tm* tm_info;

    time(&timer);
    tm_info = localtime(&timer);
    strftime(buffer1, 26, "%Y%m%d", tm_info);
    c_date = buffer1;
    strftime(buffer2, 26, "%H%M", tm_info);
    puts(buffer2);
    c_hour = buffer2;

    calc(&c_date, &c_hour);

    return 0;
}

And for example, for the time now 20180212 1045 it gives me 201802112355, when it should give me 201802121050. 例如,现在是20180212 1045,它给了我201802112355,应该给我201802121050。

What can be wrong? 有什么事吗

At present you've just copied the main prototype. 目前,您已经复制了main原型。 What does the function body of calc do? calc的功能主体有什么作用? If you had an exact copy of the main function then... 如果您拥有main功能的确切副本,那么...

int calc(int argc, char *inp[]);

argc is the number of arguments being passed into your program from the command line and inp is the array of arguments. argc是从命令行传递到程序中的参数数量,而inp是参数数组。

You're passing in &c_date as argc 您将&c_date作为argc传递

But that really depends what's within the calc function...... 但这实际上取决于calc函数中的内容……

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

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