malloc和自由具有动态变化的结构 [英] malloc and free with a dynamically changing structure

查看:117
本文介绍了malloc和自由具有动态变化的结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个动态变化的结构,我的移动指针的麻烦。
我创建了我的code在那里你可以的malloc更多的内存,这似乎是工作。
那我遇到的问题是如何增加结构,如何释放内存以及如何从结构转移到结构和打印的所有项目。

我试图测试添加和打印(似乎删除功能是有没有工作,段错误)

当我添加到结构,然后打印结构我从我添加了值的段错误。我不知道如果我从第一个结构正确地移动到下一个结构。

 的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;
#包括pointer.h/ ************
创建更多的内存大小(支柱* REC + 1)
********* /员工*创建(INT记录){
员工* new_employee =的malloc(sizeof的(员工)*(记录+ 1));返回new_employee;
}/ ************
从一个结构中的数据复制到一个新的结构
大小结构化由REC + 1相乘
*********************************************** /
员工*副本(员工*数据,INT记录){
    员工* new_employee =创建(记录);
INT I;
    对于(i = 0; I<记录;我++){
        new_employee->首先=数据 - >首先,
        new_employee->最后=数据 - >最后,
        new_employee->起始日期=数据 - >起始日期;
        new_employee-> SAL =数据 - >萨尔;
        数据++;
    }
    / **********
    需要释放旧结构
    ********************* /
    // deleteData(数据记录);返回new_employee;
}
/ ************
函数打印一切都在结构
********* /
无效printStruct(员工*数据,INT记录){
INT I;    对于(i = 0; I<记录;我++){
        的printf(\\ nEntry数:%d \\ n,I + 1);
        的printf(该员工的名字是%s%S \\ n,数据 - >首先,数据 - >最后一个);
        的printf(该员工被雇上:%S \\ N线,数据>起始日期);
        的printf(该员工化妆$%F \\ n \\ n,数据 - > SAL);
        数据++;
    }
}
/ ******************************************
功能释放旧数据库
********** /
无效deleteData(员工*数据,INT记录){
INT I;
    对于(i = 0; I<记录;我++){
        免费(数据并行>首先);
        免费(数据并行>最后一个);
        免费(数据并行>起始日期);
        数据++;
    }
    免费的(数据);
}
/ ******************************************
添加一个员工的新结构
********** /
员工*添加(员工*数据,字符* FNAME,字符* LNAME,字符*日期,浮动工资,INT记录){
员工* employeeDB =创建(记录);
employeeDB =拷贝(数据记录);
INT I;
    employeeDB ++;
    employeeDB->首先= FNAME;
    employeeDB->最后= LNAME;
    employeeDB->起始日期=日期;
    employeeDB-> SAL =工资;返回employeeDB;
}
/ ************
主要功能的启动
*************************** /诠释主要(无效){
    //保持跟踪那些在结构中的记录的数量的
INT REC = 0;
    //保持访问的结构的数目。即使有一个条目的结构还没有被访问。
INT ACC = 0;
    //保存为菜单输入信息
INT输入;
    //适用于输入查询的用户名信息
字符* FNAME;
    //适用于输入查询用户姓氏的信息
字符* LNAME;
    //适用于为开始日期的信息
字符*启动;
    //保存了工资信息;
浮萨尔;
/ **********
下一节增加了雇员的记录********** /
//这将创建的第一个条目的动态结构。
员工* first_employee =创建(REC);
first_employee->首先=FIRST;
first_employee->最后=LAST;
first_employee->起始日期=六月-20-2006;
first_employee-> SAL = 55555.55;
//增加的记录数
REC = REC + 1;员工* new_employeeDB =添加(first_employee,其中fname,lname的,JUNE-20-2010,55555.55,REC);
REC = REC + 1;
printStruct(new_employeeDB,REC);
的printf(%d个\\ N(sizeof的(员工)* REC));
}


解决方案

第一个问题:好吧......你不包括员工类型的声明。
我想第一个和最后声明为字符指针,这是一个错误。
你需要他们固定大小char数组或本行不通。
选择字符串的最大长度和申报的结构是这样的。

  typedef结构
{
    焦炭名[50];
    焦姓[50];
    ....
}雇员;

previous后:

嗯,我必须承认,我不喜欢太多贯彻事情的这种方式。
我会用一个更稳定的方法。

首先,因为它仅仅是一个项目列表,你可以用一个双向链表。
这将让你与O(1)复杂性添加和删除元素。相当不错的,确实如此。

这也将让您遍历从第一个所有项目到最后。

有关这样做,我会用一个更加面向对象导向的方法:)我知道,我们是在C,但听这个想法。

  typedef结构
{
    MYLIST * OwnerList;
    员工* previous;
    员工*下一步;    焦炭名[50];
    INT年龄;
}员工;typedef结构
{
    员工*第一;
    员工*最后;
    诠释计数;
} MYLIST;MYLIST * AllocList(){返回释放calloc(的sizeof(MYLIST),1); }无效DeleteList(MYLIST *名单)
{
    员工*电流;
    员工*接下来的;
    对于(电流=列表 - >首先,!电流= NULL;电流=下一个)
    {
        接下来=电流 - >接下来,
        免费(电流);
    }
    免费(名单);
}INT getCount将(常量MYLIST *名单)
{
    返回列表 - >计数;
}员工* AddAmployee(MYLIST *名单)
{
    员工*结果=释放calloc(sizeof的(员工),1);
    员工*最后=列表 - >最后,
    如果(即止!= NULL)
        最后所>接下来=结果;
    其他
        列表 - >首先=结果;
    result-> previous =最后;
    列表 - >最后=结果;
    ++列表 - >计数;
    result-> OwnerList =清单;
    返回结果;
}无效RemoveEmployee(员工*职员)
{
    / *我离开去除你锻炼:)找双向链表* /
    免费(员工);
}

现在,遍历所有的项目很简单:

 员工*电流;
为(电流=列表 - >首先,!电流=无效;电流=电流 - >接着)
    的printf(%S%d个\\ N型,电流>的名字,电流 - >年龄);

I am having trouble with moving my pointer in a dynamically changing structure. I have created my code where you can malloc more memory and this seems to be working. The problems that I am running into is how to add to the structure, how to free memory and how to move from structure to structure and print all items.

I am trying to test add and print (the delete function that is there does not seem to work, segfaults)

When I add to the struct and then print the struct I get a segfault from the values that I have added. I don't know if I am moving from the first struct to the next struct correctly.

#include <stdio.h>
#include <stdlib.h>
#include "pointer.h"

/********************************************
Creates more memory for size (strut * rec+1)
*********************************************/

employee *create(int record){
employee *new_employee = malloc(sizeof(employee) * (record+1));

return new_employee;    
}

/********************************************
Copies the data from one structure to a new structure with 
size "structure" multipled by rec+1
***********************************************/
employee *copy(employee *data, int record){
    employee *new_employee = create(record);
int i;
    for(i = 0; i<record;i++){
        new_employee->first = data->first;
        new_employee->last = data->last;
        new_employee->start_date = data->start_date;
        new_employee->sal = data->sal;
        data++;
    }
    /********************
    Needs to free the old struct
    *********************/
    //deleteData(data, record);

return new_employee;
}
/********************************************
Function prints everything in the struct
*********************************************/
void printStruct(employee *data, int record){
int i;

    for(i = 0; i<record; i++){
        printf("\nEntry: %d\n", i+1);           
        printf("The employee's name is %s %s\n", data->first, data->last);
        printf("The employee was hired on: %s\n", data->start_date);
        printf("The employee make $%f\n\n", data->sal); 
        data++;     
    }
}
/******************************************
Function frees the old data base
*******************************************/
void deleteData(employee *data, int record){
int i;
    for(i = 0; i<record; i++){
        free(data->first);
        free(data->last);
        free(data->start_date);
        data++;
    }
    free(data);
}
/******************************************
Adds an employee to the new structure
*******************************************/
employee *add(employee *data,char *fname, char *lname, char *date, float salary, int record){
employee *employeeDB = create(record);
employeeDB = copy(data, record);
int i;
    employeeDB++;
    employeeDB->first = fname;
    employeeDB->last = lname;
    employeeDB->start_date = date;
    employeeDB->sal = salary;

return employeeDB;
}




/**************************
Starts of the main function
***************************/

int main(void){
    //Keeps track of the number of records that are in the structure
int rec = 0;
    //Keeps the number of accesses to the structure. Even with the one entry   the structure has not been accessed. 
int acc = 0;
    //Holds the input information for the menu
int input;
    //holds the information for inputing user first name
char *fname;
    //holds the information for inputing user last name
char *lname;
    //holds the information for for the startdate
char *start;
    //holds the information for the salary;
float sal;
/*********************************
This next section adds an employee to the record

************************************/
//This creates the first entry to the dynamic structure.
employee *first_employee = create(rec);
first_employee->first = "FIRST";
first_employee->last = "LAST";
first_employee->start_date = "June-20th-2006";
first_employee->sal = 55555.55;
//increase the number of records    
rec = rec+1;

employee *new_employeeDB = add(first_employee, "fname", "lname", "JUNE-20th-2010", 55555.55, rec);
rec = rec + 1;
printStruct(new_employeeDB, rec);


printf("%d\n", (sizeof(employee)* rec));


}

解决方案

First problem: Ok... you didn't include the declaration of employee type. I guess first and last are declared as char pointers, and this is an error. You need them to be fixed size char array or this will never work. Choose a maximum length for the string and declare the structure like this.

typedef struct
{
    char name[50];
    char surname[50];
    ....
} employee;

Previous post:

Well i must admit i don't like much this way of implementing the thing. I would use a more stable approach.

First of all, since it is just a list of items, you can use a doubly linked list. This will allow you to add and remove elements with an O(1) complexity. Quite good, indeed.

This will also allow you to iterate all items from the first to the last.

For doing that i would use a more OOP oriented approach :) I know, we are in C but listen to this idea.

typedef struct
{
    MyList* OwnerList;
    Employee* Previous;
    Employee* Next;

    char name[50];
    int age;
} Employee;

typedef struct
{
    Employee* First;
    Employee* Last;
    int Count;
} MyList;

MyList* AllocList() { return calloc(sizeof(MyList), 1); }

void DeleteList(MyList* list)
{
    Employee* current;
    Employee* next;
    for (current = list->First; current != NULL; current = next)
    {
        next = current->Next;
        free(current);
    }
    free(list);
}

int GetCount(const MyList* list)
{
    return list->Count;
}

Employee* AddAmployee(MyList* list)
{
    Employee* result = calloc(sizeof(Employee), 1);
    Employee* last = list->Last;
    if (last != null)
        last->Next = result;
    else
        list->First = result;
    result->Previous = last;
    list->Last = result;
    ++list->Count;
    result->OwnerList = list;
    return result;
}

void RemoveEmployee(Employee* employee)
{
    /* i leave removal for you as exercise :) look for doubly linked list */
    free(employee);
}

Now, to iterate all items is simple:

Employee* current;
for (current = list->First; current != null; current = current->Next)
    printf("%s %d\n", current->name, current->age);

这篇关于malloc和自由具有动态变化的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆