c - 循环遍历一个动态分配的结构数组并填充每个结构
问题描述
在动态分配结构数组时,我正在努力使我的语法正确,然后我将循环遍历并传递给将从文件中填充结构的函数。任何帮助将不胜感激,因为我认为我误解了两个基本概念 1.如何最初将数组中的每个结构传递给函数 2.在函数中如何访问和分配结构字段的值。
这不会编译,这些是我得到的错误:
error: error: dereferencing pointer to incomplete type;
对于三个字段(姓名、年龄、体重)中的每一个
warning: passing argument 2 of ârgetDogâ from incompatible pointer type [enabled by default] getDog(fp, dgy + i);
void getDog( FILE *fp, struct Dog *dgy )
{
char dogName[21];
double dogAge;
double dogWeight;
fscanf(fp, "%s%lf%lf", dogName, &dogAge, &dogWeight);
strcpy(dgy->name, dogName);
dgy->age = dogAge;
dgy->weight = dogWeight;
}
int main( int argc, char *argv[] )
{
FILE *fp = fopen( argv[ 1 ], "r" );
// read in number of dogs
int n;
fscanf( fp, "%d", &n );
struct Dog {
char name[21];
double age;
double weight;
};
struct Dog *dgy = (struct Dog *)malloc(n * sizeof(struct Dog));
for (int i = 0; i < n; i++ ) {
getDog(fp, dgy + i);
}
fclose(fp);
}
解决方案
请在代码中查看下面的注释
// Some includes here - stdlib stdio
// This is needed for getDog
struct Dog {
char name[21];
double age;
double weight;
};
void getDog( FILE *fp, struct Dog *dgy )
{
// char dogName[21]; Not required
// double dogAge;
// double dogWeight;
// Check return value - ensure no buffer overrun
if (fscanf(fp, "%20s%lf%lf", dgy->name, &dgy->age, &dgy->weight) != 3) {
// Got an error - do summat about it
}
// strcpy(, dogName); - Not required as fscanf does this for you
// dgy->age = dogAge;
// dgy->weight = dogWeight;
}
int main( int argc, char *argv[] )
{
FILE *fp = fopen( argv[ 1 ], "r" );
// Is fp == NULL - if so error do summat about this
// read in number of dogs
int n;
if ( fscanf( fp, "%d", &n ) != 1 ) { // What is the point of || n < 1 ?
invalidInput();
// No point continuing to rest of code!
}
struct Dog *dgy = malloc(n * sizeof(struct Dog)); // Link below
for (int i = 0; i < n; i++ ) {
getDog(fp, dgy + i);
}
fclose(fp);
}
推荐阅读
- html - 我们可以在脚本中填充变量而不必先请求形成吗?
- firebase - FCM(Firebase Cloud Messaging)可以重新分配相同的令牌ID吗
- python - 我如何将 sql 查询传递到 python 脚本中,该脚本使用我的所有登录凭据连接到 sql oracle developer”?
- java - Java:通过分隔符将字符串拆分为哈希表
- ruby - 将块作为变量传递失败“ArgumentError:缺少块”
- matlab - 基本 Matlab for 循环
- events - 如何在实体 AFRAME 上进行焦点事件?
- spring-boot - 在运行时根据文件扩展名设置目标位置
- c# - 如何在 SQL Server 通信中禁用 C# 中的 NetBios
- sql-server - 如何修复 System.Data.SqlClient.SqlException:“用户“xx\xxxx$”登录失败”