如何在strncpy之前使用数组malloc struct

时间:2017-10-19 18:33:55

标签: c arrays struct malloc strncpy

说,我有一些像这样的结构:

struct address
{
    char city[40];
    char street[40];
    double numberofhouses;
};

struct city
{
    struct address * addresslist;
    unsigned int uisizeadresslist;
    unsigned int housesinlist;
};

struct city *city= malloc(sizeof(struct city);

我想以可以向结构写入30个地址的方式初始化它。

我从.txt文件中读取地址并将其写入结构。 如果需要,我还想动态重新分配更多内存来读取所有地址。

我是malloc的新手并且还搜索了一些例子。但我改编它们的方式总是失败。

我做错了什么?似乎没有内存被分配,因此strncpy命令无法写入结构。

如果我使用静态结构,那么一切正常。

1 个答案:

答案 0 :(得分:0)

struct address* addresslist本身就是struct city内的指针,如果你想要保存malloc类型,你还需要struct address内存。

#define NUM_ADDRESSES 30

struct city *city= malloc(sizeof(struct city);
if (city != NULL)
{
  city->addresslist = malloc(sizeof(struct address) * NUM_ADDRESSES);
  if (city->addresslist == NULL)
  {
    // handle error
  }
}
else
{
  // handle error
}

// now I can safely strcpy into the city->addresslist. Just be sure not
// to copy strings longer than 39 chars (last char for the NUL terminator)
// or access addresses more than NUM_ADDRESSES-1
strcpy(city->addresslist[0].city, "Las Vegas");
strcpy(city->addresslist[0].street, "The Strip");
....

// things have changed, I need to realloc for more addresses
struct address newAddrs* = realloc(city->addresslist, NUM_ADDRESSES*2);
if (newAddrs != NULL)
{
  city->addresslist = newAddrs;
}
else
{
  // handle error
}

....

free(city->addresslist);
free(city);