2017-10-19 101 views
1

说之前使用数组的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命令失败了ro写入结构。

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

+1

“我从.txt文件读取地址并将它们写入结构。” - >发布代码。 “我改编他们的方式总是失败。”发布失败的尝试。 “我在哪里做错了什么?” - >你没有发布足够的代码来显示问题。 – chux

回答

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);