邮政编码使用结构 [英] Postal code using structures

查看:103
本文介绍了邮政编码使用结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个存储邮政编码的结构,但是我收到此错误:"c:15:11:错误:分配给具有数组类型的表达式 h-> array = malloc(sizeof(PostalCode)* size);"

I'm trying to make a a structure that stores postal codes but I receive this error: "c:15:11: error: assignment to expression with array type h->array = malloc(sizeof(PostalCode)*size);"

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

typedef struct PostalCode
{
    int size;
    char *array[5];
} PostalCode;

void main()
{
    int size = 5;
    PostalCode *h = malloc(sizeof(PostalCode));
    h->size = size;
    h->array = malloc(sizeof(PostalCode)*size);
}

推荐答案

该结构已经包含5个指针数组作为其数据成员

The structure already contains an array of 5 pointers as its data member

typedef struct PostalCode
{
    int size;
    char *array[5];
    ^^^^^^^^^^^^^^
} 

因此您无需分配它.

如果要使用此数组存储例如类型为PostalCode的5个对象 (尽管在这种情况下,如果数组的类型为PostalCode *array[5]会更好),那么您可以编写

If you want to use this array to store for example 5 object of type PostalCode (though in this case it would be better if the array has type PostalCode *array[5]) then you can write

for ( int i = 0; i < 5; i++ )
{ 
    h->array[i] = malloc( sizeof( PostalCode ) );
}

这篇关于邮政编码使用结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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