c - 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");
}
解决方案
...想将数组的所有元素设置为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)
。不要花时间分配未使用的数组成员。
推荐阅读
- node.js - 代码错误:从 node.js 中的 xlsx 表中删除重复值
- c# - 将字符串初始化为 "" 或 "".ToString() 之间的区别 - 我应该使用哪一个?
- java - 如何在使用 jdbcTemplate 查询多行的条件中设置参数
- node.js - 我可以使用 docker 从外部世界隐藏我的节点 js 服务器吗
- c# - 防止表单背面颜色闪烁的可靠方法应该始终不可见?
- c++ - 拔出设备时串口无限期阻塞的 CloseHandle 方法
- c# - 使用 c# 桌面应用程序的 firestore 进行身份验证
- bash - 如何将动态 json 对象添加到 jq bash
- javascript - 在 mongodb 中,作为密钥而不是匿名用户的用户名和密码传递什么?
- rest - 如果有 L4 / L7 平衡器,如何知道端点已关闭?