过去,我一直在努力理解指针算术,类型转换和结构数组,有时即使该程序可以运行,但从技术上来说还是不正确的,因此我只想运行你们编写的这段代码并确保我正确理解所有概念。
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int id, jobType;
float salary;
} Employee;
Employee * readFileInfo(FILE *fp)
{
int numEmployees = 0;
fscanf(fp, "%d", &numEmployees); //find the int at the start of the file to indicate how many employees there are
int *array = malloc( (sizeof(int)) + ( sizeof(Employee) * numEmployees ) ); //allocate an extra spot for an integer
*array = numEmployees; //hide the number of employees one integer behind the start of the array, increment on next line
array++;
Employee *test = (Employee *) array;
for(int i = 0; i < 3; i++)
fscanf(fp, "%d %d %f", &test[i].id, &test[i].jobType, &test[i].salary); //loop through and assign each value to its proper variable
return test;
}
Employee * getEmployeeByID(Employee *arr, int ID)
{
for(int i = 0; i < *((int*)arr - 1); i++)
if(arr[i].id == ID)
return ((arr) + i); //returns address of specified employee
return 0;
}
void setID(Employee *p, int ID)
{
p->id = ID;
printf("\nset successfuly\n");
}
int getSize(Employee *arr)
{
return *((int*)arr - 1); //returns the int value hidden before start of array
}
void getAvgSalary(Employee *arr) //calculates average salary, prints out all employees who make more than that
{
float total = 0, avg = 0;
for(int i = 0; i < getSize((Employee*)arr); i++)
total += arr[i].salary;
avg = total / (float)getSize((Employee*)arr);
for(int i = 0; i < getSize((Employee*)arr); i++)
if(arr[i].salary >= avg)
printf("ID: %d has above the avg salary with a salary of $%.2f\n", arr[i].id, arr[i].salary);
}
int main(void)
{
FILE *fp = fopen("test.txt", "r+");
Employee *array = readFileInfo(fp);
Employee *emp2 = getEmployeeByID(array, 2);
setID(emp2, 5);
getAvgSalary(array);
}
test.txt
3 1 5 20000 2 1 100000 3 3 50000
基本上,该程序应该打开test.txt,调用readFileInfo来查找文件中的第一个整数(表示要跟随的雇员数),使用3种东西为结构数组分配内存:那个大小号乘以员工结构的大小,然后在数组开始之前添加一个额外的整数以“隐藏”该大小变量。之后,在数组上调用各种函数以进行类型转换/指针算法实验
任何帮助,更正,建议,观察或回应都是很棒的!
答案 0 :(得分:1)
代码不正确。假设float
改为double
,则整个结构将具有double
的对齐要求,在x86-64上为8字节。但是您已将其强制对齐4。它具有未定义的行为,这意味着它可以工作,也可以fail catastrophically。
幸运的是,此黑客的需求为零。只需将struct
与 flexible数组成员一起使用即可>
typedef struct
{
int id, jobType;
float salary;
} Employee;
typedef struct {
size_t numEmployees; // use size_t for array sizes and indices
Employee employees[];
} EmployeeArray;
// allocate sizeof (EmployeeArray) space for the struct
// and sizeof (Employee) space for each array element
EmployeeArray *array = malloc(sizeof *array + sizeof (Employee) * numEmployees);
array->numEmployees = numEmployees;
array->employees[0] = ...