0

我有一个将成为链表的结构。但起初我无法从内部结构中读取值。听起来很复杂,但这里是代码:

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

struct Address
{
    char city[50];
};

struct Task
{
    char fullName[255];
    struct Address address;
};

struct TaskList
{
    struct Task* task;
    struct TaskList* next;
};

struct Task createTask()
{
    struct Task task;
    struct Address address;
    printf("Enter full name: ");
    scanf("%s", task.fullName);
    printf("Enter the city: ");
    scanf("%s", address.city);
    task.address = address;

    return task;
}

void addTask(struct TaskList *head)
{
    struct TaskList* temp;
    struct Task task = createTask();
    temp->task = &task;
    temp->next = head;
    head = temp;
}

int main()
{
    struct TaskList *head;
    head = NULL;
    addTask(head);
    printf("%s", head->task->address.city);

    return 0;
}

当我启动应用程序并输入一些数据时,进程崩溃并显示以下代码:

进程返回 -1073741819 (0xC0000005) 执行时间:11.102 s

事实上,我应该如何处理内部结构及其领域?

4

4 回答 4

2

taskcreated by是在栈上分配的,在 function( ) 结束createTask后会被释放。createTask改为使用malloc

于 2013-11-08T11:19:21.283 回答
1

您应该通过指针将头指针传递给 addTask() 以在其中更改它:

struct TaskList* addTask(struct TaskList **head)

并将其设置在其中:

*head = temp;

并且 createTask() 必须探索 malloc() 并且对于scanf()调用必须使用指向变量的指针:

struct Task *createTask()
{
    struct Task *task = malloc(sizeof(struct Task));
    printf("Enter full name: ");
    scanf("%s", &task->fullName);
    printf("Enter the city: ");
    scanf("%s", &task->address.city);
    return task;
}

由于地址结构是任务的一部分 - 只有一次调用 malloc()。

于 2013-11-08T11:20:49.910 回答
0

此代码存在多个内存问题,这里是其中之一的解释和解决方案。

Valgrind 显示:

==1249== Invalid read of size 8
==1249==    at 0x40051B: main (/tmp/t.c:48)
==1249==  Address 0x0 is not stack'd, malloc'd or (recently) free'd

当您在第 48 行打印时,它看起来head仍然为 null。不会addTask更改. 像这样修复它:headmain

struct TaskList* addTask(struct TaskList *head)
{
    struct TaskList* temp = malloc(sizeof *temp);
    struct Task* task = malloc(sizeof *task);
    *task = createTask();
    temp->task = task;
    temp->next = head;
    return temp;
}
int main()
{
    struct TaskList *head;
    head = NULL;  
    head = addTask(head);
    printf("%s", head->task->address.city);
    return 0;
}
于 2013-11-08T11:16:22.213 回答
0
struct Address
{
    char city[50];
};

struct Task
{
    char fullName[255];
    Address address;
 };

struct TaskList
{
    Task* task;
    TaskList* next;
 };

 struct Task createTask()
 {
    Task task;
    Address address;
    printf("Enter full name: ");
    scanf("%s", task.fullName);
    printf("Enter the city: ");
    scanf("%s", address.city);
    task.address = address;

   return task;

}

你的“头”指针也为空,正确初始化它

尝试以这种方式使用它删除关键字“struct”,它必须工作正常

于 2013-11-08T11:20:22.773 回答