Как назначить значение с помощью scanf члену переменной типа Struct, массив которой создается динамически - PullRequest
0 голосов
/ 01 мая 2020

Изображение визуализации кода

Моя основная проблема заключается в том, как передать входные данные, используя scanf, в члены coeff и exp, объявленные в массиве терминов, на который ссылается переменная-член Poly с именем как ptr, и на эту переменную 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));
    }
} 

1 Ответ

1 голос
/ 01 мая 2020

Существует много проблем.

Это исправленный код с пояснениями в конце строки комментариев. Комментарии без ** показывают улучшения, которые не были фактическими ошибками

#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
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...