简体   繁体   English

在C中将指针分配给结构的问题

[英]problem assigning a pointer to a struct in C

This is the error that I get in my program: 这是我在程序中遇到的错误:

[Error] cannot convert 'struct(*)[5] ' to 'struct* {aka Contact*}' in assignment

When I try to do this: 当我尝试这样做时:

typedef struct Contact{
    char FName[];
    char LName[];
} cont;                                                                    

cont AddressBook[SIZE];                                                   

int main(){ 
    cont *adbook = (cont *)calloc (SIZE, sizeof(cont));
    adbook=&AddressBook
}

How can I assing the address of my array of structs to my pointer??? 如何将结构数组的地址分配给指针?

Hope you can help me. 希望您能够帮助我。

When we declare arrays, It's variable name is actually already a pointer pointing it's address. 当我们声明数组时,它的变量名实际上已经是一个指向其地址的指针。

So when you're performing 所以当你表演时

adbook=&AddressBook;

It is like saying point to the address of the pointer which points to AddressBook. 这就像说指向指向AddressBook的指针的地址一样。 This is Invalid assignment. 这是无效的分配。 (Somewhat like assigning Pointer to Pointer (**) to a single Pointer(*)). (有点像将Pointer to Pointer(**)分配给单个Pointer(*))。

This can be solved easily by removing the '&' operator while assigning to the pointer. 通过在分配给指针的同时删除'&'运算符,可以轻松解决此问题。 Making it : 进行中 :

adbook=AddressBook;

That would simply mean "Point to the location of AdressBook. 这仅表示“指向AdressBook的位置。

Happy Coding ! 编码愉快!

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

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