Adding two members of a struct together

为君一笑 提交于 2019-12-24 07:35:56

问题


    typedef struct Int40
{
  // a dynamically allocated array to hold a 40
  // digit integer, stored in reverse order
  int *digits;
} Int40;

in main I have these functions implemented, and loadCryptoVariable and loadHwConfigVariable each return a 40 digit value

Int40 *p;
  Int40 *q;
  Int40 *r;
    p = loadCryptoVariable("cryptoVarFile");
      q = loadHWConfigVariable(0);
     r = kw26Add( p, q);

However, I can't figure out how to add the two together..(side note: I am aware I shouldn't malloc like that and use a more defined way to do it, however, I'm just attempting to figure out the add at the moment)

Int40 *kw26Add(Int40 *p, Int40 *q)
{
    Int40 *result;
    result = malloc(300);
    result->digits = malloc(300);

    result->digits = p->digits + q->digits;

     return result;
}

回答1:


I'm not sure I understand the question, but as I read it, you would need to iterate through the array. For example:

for (int i = 0; i < 40; ++i)
    result->digits[i] = p->digits[i] + q->digits[i];


来源:https://stackoverflow.com/questions/49205149/adding-two-members-of-a-struct-together

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!