【问题标题】:Creating a Calculator using command line interface and malloc,使用命令行界面和 malloc 创建计算器,
【发布时间】:2021-12-25 23:19:16
【问题描述】:

我正在研究 malloc 和命令行界面,我必须在其中创建和简单的计算器。我已经成功运行了程序,但我想从主程序打印我的结果,而不是从函数中,我无法从主程序运行它。每次我运行它都会显示垃圾值。出了什么问题?

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stdint.h>

typedef struct {
    int num1;
    int num2;
    uint8_t *ope;
    int result;
} Calc;

void SI( Calc c) {
    if(strcmp(c.ope,"add")==0)
    {
        printf(" result is : %d\n :",c.result = (c.num1 + c.num2 ));
    }
    else if(strcmp(c.ope,"sub")==0)
    {
        printf(" result is :%d\n :",c.result = (c.num1 - c.num2 ));
    }
}

int main(int argc,char *argv[]) {
    Calc *pCalc = (pCalc *) malloc(sizeof(Calc));

    pCalc ->ope = (argv[1]);
    pCalc ->num1   = atoi (argv[2]);
    pCalc ->num2   = atoi (argv[3]);
    SI(*pCalc );

    printf("result is: %d\n", pCalc ->result);  // I want to print result here

    free(pCalc );

    return 0;
}

【问题讨论】:

  • 使函数SI返回结构或int结果。

标签: c linux struct malloc command-line-interface


【解决方案1】:

SI(*pCalc ); 将结构的值(本质上是一个副本)传递给SI,并且void SI( Calc c) 声明SI 具有一个参数c,该参数被初始化为传递的值。 SI 中对c 的更改仅影响参数c;它们不会影响main 中的结构。

你可以把SI(*pCalc );改成SI(pCalc);,让它传递pCalc的地址而不是它的值,你可以把函数声明改成void SI(Calc *c),这样它的参数c就是一个指针,初始化为传递的地址。在SI 中,将c. 更改为c-&gt;. 运算符访问结构的成员,而 -&gt; 运算符访问指向的结构的成员。

或者,您可以修改SI 的返回类型,使其返回一些结果——修改结构(返回类型Calc)或只是单个结果(返回类型int)。然后在函数中添加return 语句以返回值,并且在main 例程中,您可以使用x = SI(*pCalc); 将返回值分配给x

【讨论】:

  • 成功了,非常感谢您的帮助
【解决方案2】:

您可以将pCalc 的指针传递给函数SI(如@EricPostpischil 所建议的那样)并将其result 设置在那里。

此外,还添加了一些修复。请阅读cmets// CHANGE HERE

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>

typedef struct
{   int num1;
    int num2;
    uint8_t *ope;
    int result;
} Calc;

// CHANGE HERE - accept pointer argument
void SI(Calc* c) {
    if (c == NULL)
    {
        return;
    }
    // CHANGE HERE - use strncmp instead of strcmp
    if (strncmp(c->ope, "add", 3) == 0)
    {
        c->result = (c->num1 + c->num2);
    }
    else if (strncmp(c->ope, "sub", 3) == 0)
    {
        c->result = (c->num1 - c->num2);
    }
}

int main(int argc,char *argv[]) {
    // CHANGE HERE - command line arguments validation
    if (argc != 4)
    {
        printf("Unexpected number of arguments\n");
        exit(1);
    }

    // CHANGE HERE - pCalc -> Calc
    Calc *pCalc = (Calc *) malloc(sizeof(Calc));

    pCalc ->ope = (argv[1]);
    pCalc ->num1   = atoi (argv[2]);
    pCalc ->num2   = atoi (argv[3]);
    SI(pCalc);  // CHANGE HERE - pass the pointer

    printf("result is: %d\n", pCalc->result);  // I want to print result here

    free(pCalc);

    return 0;
}

【讨论】:

  • 非常感谢您的帮助,祝您有美好的一天
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-20
  • 1970-01-01
  • 2010-11-23
相关资源
最近更新 更多