簡體   English   中英

如何使用 scanf 將值分配給其數組是動態創建的 Struct 類型變量的成員

[英]How do i assign a value using scanf to a member of a Struct type variable whose array is created dynamically

代碼可視化圖像

我的主要問題是如何使用 scanf 對在術語數組中聲明的 coeff 和 exp 成員進行輸入,這些成員由名為 ptr 的 Poly 變量成員引用,並且該 Poly 變量由指針 p 進一步引用。

#include <stdio.h>

struct Term
{
    int coeff;
    int exp;
};

struct Poly
{
    int terms;
    struct Terms *ptr;
};

int main(void)
{

    return 0;
}
//creating the array dynamically
struct Term *createPoly()
{
    struct Poly *p;
    p = (struct Poly *)malloc(sizeof(struct Poly));
    printf("Input the number of terms in the polnomial:\n");
    scanf("%d", p->terms);
    p->ptr = (struct Term *)malloc(sizeof(struct Term) * p->terms);

    return p;
}
//inputting the values
void input(struct Poly *p)
{
    for (int i = 0; i < p->terms; i++)
    {
        printf("Input the term %d coefficient and exponent value!", i);
        scanf("%d%d", &(p->(ptr + i).coeff));
    }
} 

有很多問題。

這是更正的代碼,行末注釋中有解釋。 沒有**的評論顯示了不是實際錯誤的改進

#include <stdio.h>
#include <stdlib.h>                   // ** you forgot this

struct Term
{
  int coeff;
  int exp;
};

struct Poly
{
  int nbofterms;                      // nbofterms is better than terms
  struct Term* ptr;                   // ** use Term instead of Terms
};

int main(void)
{

  return 0;
}

//creating the array dynamically
struct Poly* createPoly()             // ** you want a struct Poly and not a struct Term
{
  struct Poly* p;
  p = malloc(sizeof(struct Poly));    // (struct Poly*) cast not needed
  printf("Input the number of terms in the polnomial:\n");
  scanf("%d", &p->nbofterms);             // & added
  p->ptr = malloc(sizeof(struct Term) * p->nbofterms);  // cast not needed

  return p;
}

//inputting the values
void input(struct Poly* p)
{
  for (int i = 0; i < p->nbofterms; i++)
  {
    printf("Input the term %d coefficient and exponent value!", i);
    scanf("%d", &p->ptr[i].coeff);    // ** only one %d and expression corrected
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM