C 中结构体的动态大小数组问题

发布于 2025-01-11 23:22:24 字数 2854 浏览 1 评论 0原文

我正在尝试创建一个结构数组,该数组将随着用户想要输入更多内容而扩展。这是结构:

struct employee{
    char name[20];
    int id;
    char job[35];
    float basePay;
    float overTimePay;
    float totalPay;
    float totalPayBenefits;
    int year;
    char agency[15];
    int count;
};

我在这里实现了扩展结构数组(只要用户指定这样做,就会继续向数组添加结构):

struct employee *createEmployees(){
    //Declare and initialize necessary variables
    int i = 1;
    char continueChar = 'y';
    struct employee *employeeList = malloc(sizeof(employeeList));
    //While user selects continue
    while(continueChar == 'y'){
        char temp;
        //reallocate based on how many times the user has continued
        if(i != 1){
            employeeList = realloc(employeeList, i * sizeof(employeeList));
        }
        printf("Enter Employee %d name: ", i);
        //Clear char from input
        scanf("%c",&temp);
        //Set employee name
        scanf("%[^\n]", employeeList[i-1].name);
        //Get user continue selection
        printf("Would you like to enter another employee? (y/n): ");
        scanf(" %c", &continueChar);
        i++;
    }
    //Keep a count of all employees in list in the first employee cell
    employeeList[0].count = i - 1;
    //Return formed employees struct array
    return employeeList;
}

当我测试所有名称都在 main 中设置时,它们似乎是。 main 中的计数也是正确的。当我将这个结构数组传递给一个单独的函数来读取文件并将内容输入到结构数组中时,我的问题就出现了。 这里是 main:

int main(){
    //Declare an array to hold all employees
    struct employee *employeeList = createEmployees();
    //Get userID from txt file
    getID(employeeList);
}

这里是 getID (该函数将搜索整个 employeeInformation.txt 文件,直到找到给定名称的匹配项。它将重复此 X 次,其中 X 是存储在 employeeList[0].count 中的计数):

void getID(struct employee *employeeList){
    char line[100];
    int stop = 1;
    FILE *fptr = fopen("employeeInformation.txt", "r");
    if(!fptr){
        perror("Error");
        exit(0);
    }
    //skip first line
    fgets(line, 100, fptr);
    for(int i = 0; i < employeeList[0].count; i++){
        while (!feof(fptr) && stop) {
            int id;
            char name[20];
            char job[35];
            fscanf(fptr, "%d\t%[^\t]%[^\n]", &id, &name, &job);
            printf("%d\t%s\t%s\n", id, name, job);
            if(strcmp(employeeList[i].name, name) == 0){
                employeeList[i].id = id;
                strcpy(employeeList[i].job, job);
                stop = 0;
            }
            fgets(line, 100, fptr);
        }
        fseek(fptr, 0, SEEK_SET);
        stop = 1;
    }
    fflush(fptr);
    fclose(fptr);
}

所以我的问题是employeeList[0].count 似乎没有正确传递。我可以在 main 中以及在 getID 方法中打开文件之前正确获取计数,但是在我打开文件之后,它说该值等于某个很长的数字。我认为问题出在两个地方之一;要么我错误地分配了结构体数组,要么我错误地传递了结构体数组。我尝试了多种方法来尝试解决此问题,但我似乎无法理解问题所在。任何对此的帮助将不胜感激!

I'm trying to create an array of structs that will expand as the user wants to input more. Here is the struct:

struct employee{
    char name[20];
    int id;
    char job[35];
    float basePay;
    float overTimePay;
    float totalPay;
    float totalPayBenefits;
    int year;
    char agency[15];
    int count;
};

I have implemented the expanding struct array here (this will continue adding structs to the array for as long as the user specifies to do so):

struct employee *createEmployees(){
    //Declare and initialize necessary variables
    int i = 1;
    char continueChar = 'y';
    struct employee *employeeList = malloc(sizeof(employeeList));
    //While user selects continue
    while(continueChar == 'y'){
        char temp;
        //reallocate based on how many times the user has continued
        if(i != 1){
            employeeList = realloc(employeeList, i * sizeof(employeeList));
        }
        printf("Enter Employee %d name: ", i);
        //Clear char from input
        scanf("%c",&temp);
        //Set employee name
        scanf("%[^\n]", employeeList[i-1].name);
        //Get user continue selection
        printf("Would you like to enter another employee? (y/n): ");
        scanf(" %c", &continueChar);
        i++;
    }
    //Keep a count of all employees in list in the first employee cell
    employeeList[0].count = i - 1;
    //Return formed employees struct array
    return employeeList;
}

When I test that all the names are set in main it appears that they are. The count also is correct in main. My problem comes when I pass this array of structs to a separate function to read a file and input the contents into the struct array.
Here is main:

int main(){
    //Declare an array to hold all employees
    struct employee *employeeList = createEmployees();
    //Get userID from txt file
    getID(employeeList);
}

And here is getID (This function will search the entire employeeInformation.txt file until it finds a match for the given name. It will repeat this X times where X is the count stored in employeeList[0].count):

void getID(struct employee *employeeList){
    char line[100];
    int stop = 1;
    FILE *fptr = fopen("employeeInformation.txt", "r");
    if(!fptr){
        perror("Error");
        exit(0);
    }
    //skip first line
    fgets(line, 100, fptr);
    for(int i = 0; i < employeeList[0].count; i++){
        while (!feof(fptr) && stop) {
            int id;
            char name[20];
            char job[35];
            fscanf(fptr, "%d\t%[^\t]%[^\n]", &id, &name, &job);
            printf("%d\t%s\t%s\n", id, name, job);
            if(strcmp(employeeList[i].name, name) == 0){
                employeeList[i].id = id;
                strcpy(employeeList[i].job, job);
                stop = 0;
            }
            fgets(line, 100, fptr);
        }
        fseek(fptr, 0, SEEK_SET);
        stop = 1;
    }
    fflush(fptr);
    fclose(fptr);
}

So my problem is that employeeList[0].count doesn't seem to be passing correctly. I can get the count correctly in main and before I open a file within the getID method, but after I open a file it says the value is equal to some very long number. I think the problem is in one of two places; either I'm allocating the struct array incorrectly or I'm passing the struct array incorrectly. I've tried numerous methods to try to fix this but I just can't seem to wrap my head around what the issue is. Any help with this would be greatly appreciated!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

枫以 2025-01-18 23:22:24

(employeeList) 的大小是多少?

struct employee *employeeList = malloc(sizeof(employeeList));

试试这个:

struct employee *employeeList = malloc(sizeof(*employeeList));

What's the sizeof(employeeList)?

struct employee *employeeList = malloc(sizeof(employeeList));

Try this:

struct employee *employeeList = malloc(sizeof(*employeeList));
风蛊 2025-01-18 23:22:24
  1. 内存分配不对。
/* create employee list with 4 elements */
size_t members_count = 4;
struct employee *employeeList = malloc(sizeof(struct employee) * members_count); 
  1. 总是(!!!)检查 malloc 返回的内容
/* create employee list with 4 elements */
size_t members_count = 4;
struct employee *employeeList = malloc(sizeof(struct employee) * members_count);
if (NULL == employeeList)
    return;
  1. 如果您想动态增加成员数量,最好选择其他数据结构。不是数组。查看列表。因为数组应该放在连续的块中,在某些情况下这对内存不利。
  1. Memory allocation isn't right.
/* create employee list with 4 elements */
size_t members_count = 4;
struct employee *employeeList = malloc(sizeof(struct employee) * members_count); 
  1. Always(!!!) check what malloc returns
/* create employee list with 4 elements */
size_t members_count = 4;
struct employee *employeeList = malloc(sizeof(struct employee) * members_count);
if (NULL == employeeList)
    return;
  1. If you want to increase dynamically number of members better choose other data structure for that. Not array. Take a look at lists. Because array should be placed in continuous block and this not good for memory in some cases.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文