首页 > 解决方案 > How to set all 0s into an array declared through structure (C)?

问题描述

while I was practicing with C programming I found a problem about arrays with structs. In particular, I'm going to make a program to operate with different polynomials; so I declared a struct "Pol" which contains the variable "order" and the array "coefficients". Then I'm going to make soe operations with polynomials (for example the sum between two of them). The problem is about how to declare the array "coefficients" in the structure, because when I want to sum two polynomials I want to set all the elements of the array to 0 (to solve the problem about the sum of two polynomials with differents orders). I know how to set 0s into an array declared in main function (setting a single value to 0, and then all the others are automatically set to 0). But how can I do the same with the structure?

Thank you in advance to all people who are going to help me.

I public the code (not finished) below:

#include <stdio.h>
#include <math.h>

#define N_MAX 100

typedef struct
{
  float coefficients[N_MAX];
  int order;
} Pol;

void println(int n);
void readPol(Pol* pol);

int main(int argc, char const *argv[])
{
  Pol p1, p2, pS;

  readPol(&p1);
  return 0;
}

void readPol(Pol* pol)
{
  printf("Polynomial order: ");
  scanf("%d", &pol->order);
  println(1);

  for(int i = pol->order; i >= 0; i--)
    {
      printf("Coefficient of x^[%d]: ", i);
      scanf("%f", &pol->coefficients[i]);
    }
}

void println(int n)
{
  for(; n > 0; n--)
    printf("\n");
}

标签: carraysstruct

解决方案


...想将数组的所有元素设置为0

初始化(在声明时分配),各种选择。

Pol pol1 = { .order = 0, .coefficients = { 0 } };    // Declare members in desired order
Pol pol2 = { .coefficients = { 0 }, .order = 0 };
Pol pol3 = { .order = 0, .coefficients = { 0.0f } }; // A float constant for clarity
Pol pol4 = { { 0.0f }, 0 };                          // Order matches declaration 
Pol pol5 = { 0 };                                    // All set to 0

请注意,使用部分显式初始化器,剩余的成员/数组元素将获得 0 值。(整数类型为 0,FP 类型为 0.0,指针类型为一些空指针。)

在 C 中,没有部分初始化,全有或全无。


分配,直接的解决方案是使用循环。

pol->order = 0;
for(i = 0; i < N_MAX; i++) {
  pol->coefficients[i] = 0.0f;
}

但为什么?所有代码需要是

pol->order = 0;
pol->coefficients[0] = 0.0f;

拥有一个.order成员的目的是将工作扩展到数组的使用大小,以及在readPol(Pol* pol)和中完成println(int n)。不要花时间分配未使用的数组成员。


推荐阅读