简体   繁体   English

在结构的“数组”中访问和分配结构的每个部分中的值?

[英]Accessing and assigning values in each part of the struct in an “array” of structs?

So I have an assignment to allocate enough memory to store a set of structs with different values in them. 因此,我分配了足够的内存来存储一组具有不同值的结构。 I am only allowed to call malloc once. 我只允许调用一次malloc。

A have a struct that looks like this: 一个结构如下所示:

typedef struct ObjectTag Object;
struct ObjectTag
{
    char *stringA[20];
    char *stringB[30];
    char *stringC[5];
    unsigned short num;
};

For my malloc call I am doing 对于我的malloc电话,我正在做

Object *myObjArray;
myObjArray= (Object*)malloc(numObjects * sizeof(Object));

I am trying to get information from an infile to place into my structs. 我正在尝试从文件中获取信息以放入我的结构中。 Thus I am doing 因此我在做

fscanf(inFile, " %s", (*Object)[i].stringA);
fscanf(inFile, " %s", (*Object)[i].stringB);
fscanf(inFile, " %s", (*Object)[i].stringC);
fscanf(inFile, " %hu", (*Object)[i].num);

and so on in a loop. 以此类推。

But when I try to compile I get this error 但是当我尝试编译时出现此错误

format '%s' expects argument of type 'char *', but argument 3 has type 'char **'

and also this for the last one 这也是最后一个

format '%hu' expects argument of type 'short unsigned int *', but argument 3 has type 'int'

I have no idea what I'm doing wrong. 我不知道我在做什么错。

Notes that may be relevant: 可能相关的注释:

  • The infile has an expected format to it infile具有预期的格式
  • I have counted how many structs I needed as noted by the numObjects in the malloc call 我已经计算了需要多少个结构,如malloc调用中的numObjects所示

char *stringA[20] is NOT a string of 20 (or 19) characters. char *stringA[20]不是20(或19)个字符的字符串。 It is an array of 20 strings of unspecified length . 它是20个未指定长度的字符串的数组 Are you sure this is what you want? 您确定这就是您想要的吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM