简体   繁体   English

将结构复制到结构数组

[英]Copy a struct to a struct array

Hey guys I need some help. 嗨,我需要一些帮助。 I'm trying to store a SCar struct into an array of Scar inside the SOwner structure, for each different SOwner, though I'm getting this error: 我正在尝试为每个不同的SOwner将SCar结构存储到SOwner结构内的Scar数组中,尽管出现此错误:

Incompatible types when assigning to type 'Scar' from type 'struct SCar *' 从“ struct SCar *”类型分配给“ Scar”类型时,类型不兼容

Here's some code : 这是一些代码:

typedef struct {
char name[40];
SCar cars [100];
} SOwner;

typedef struct {
char color[40];
char brand[12];
} SCar;

SOwner *ownerPTR;
SCar *carPtr

void function(){
for(i=0; i<10 ; i++){
    (ownerPtr)->cars[i] = (carPtr+i);   // Problem here <<<--
}

Is there any simple way to make this work out? 有没有简单的方法可以解决这个问题? Thanks 谢谢

You must dereference the pointer on the right hand side to generate a value of type SCar . 您必须取消引用右侧的指针才能生成SCar类型的值。

Like so: 像这样:

ownerPtr->cars[i] = carPtr[i];

or 要么

ownerPtr->cars[i] = *(carPtr + i);

But the latter is just a more complicated way to write the former, so just use indexing. 但是后者只是编写前者的一种更复杂的方法,因此只需使用索引即可。

you have to define an array of pointers 您必须定义一个指针数组

typedef struct {
    char name[40];
    SCar * cars [100];
} SOwner;

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

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