如何将结构初始化为指向的结构

时间:2018-05-15 20:22:15

标签: c arrays pointers data-structures

合十!我想用指向我的项结构的指针初始化我的struct数组位置0 myList.items [0],但是当我从print函数打印出来时,它会在相关位置打印出乱码。它改变了之前初始化的内容(用于测试),所以我知道它可以部分工作,但是什么导致输出不良以及应该更改什么?

之前:

----我的购物清单---------

1 - 巧克力40 100克

2 - Fishsauce 9升

后:

----我的购物清单---------

1 - c┴®¶²`128565603■lüIv

2 - Fishsauce 9升

typedef struct{
        char name[20];
        int amount;
        char amountType[10];
}item;

typedef struct{
        item *items[5];
        int length;
}list;

int addItemToList(list *myList);

main(void)
{
    list myList;
    myList.length = 0;
    for(int i; i<5;i++)
    {
        myList.items[i] = NULL;
    }
    addItemToList(&myList);
    return 0;
}


int addItemToList(list *myList)
{
    item newItem = {"Potatoes",2, "kg"};
    myList->items[myList->length]=&newItem; //Something wrong here?
    myList->length++;
    printf ("Added [%s %i %s] as #%i.", newItem.name, newItem.amount,newItem.amountType, myList->length);
return 0;
}

3 个答案:

答案 0 :(得分:1)

此:

int addItemToList(list *myList)
{
    item newItem = {"Potatoes",2, "kg"};

在堆栈上分配newItem。这意味着当addItemToList完成时,它的内存将消失,因此&amp; newItem将在以后指向乱码。它仍然可以在addItemToList中运行代码,但之后内存内容将被替换为任何其他被调用的函数。

您可以使用malloc为newItem分配一些内存,也可以在main函数的堆栈中分配newItem,并将指向newItem的指针传递给任何其他被调用的函数。

答案 1 :(得分:0)

您无法初始化堆栈上的结构,然后将指向该结构的指针传递给另一个结构,该结构的生命周期比打开的堆栈框架长。函数返回后,分配item的堆栈帧将关闭,字段的指定值将消失。

你需要一个具有堆分配结构的初始化函数,如下所示:

item* item_new(const char* name, int amount, const char* amountType);

然后你的初始化函数应该:

  1. 调用Malloc以获取struct的大小,
  2. nameamountType字符串复制到结构。
  3. amount复制到结构。
  4. 然后你可以这样做:myList->items[myList->length]=newItem;,其中newItem是由你的init函数创建的。

答案 2 :(得分:0)

你正在混合堆栈和堆内存,我为你重写它,它应该给你一些错误的感觉。另外总是免费分配内存,而不是java:

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

typedef struct{
        char name[20];
        int amount;
        char amountType[10];
}item;

typedef struct{
        item *items[5];
        int length;
}list;

int addItemToList(list *myList);

int main(void)
{
    list myList;
    myList.length = 0;
    for(int i; i<5;i++)
    {
        myList.items[i] = 0;
    }

    addItemToList(&myList);

    for(int i; i<myList.length; i++)
    {
        free(myList.items[i]);
    }

    return 0;
}


int addItemToList(list *myList)
{
    item* newItem = malloc(sizeof(item));
    strcpy(newItem->name, "Potatoes");
    newItem->amount = 2;
    strcpy(newItem->amountType, "kg");
    myList->items[myList->length++] = newItem; //Something wrong here?
    printf ("Added [%s %i %s] as #%i.\n", newItem->name, newItem->amount, newItem->amountType, myList->length);
    return 0;
}
相关问题