简体   繁体   English

指针帮助:将指向结构的指针取消引用以访问其中的数据

[英]Pointer help: dereferencing a pointer to a struct accessing data within it

I'm having some trouble wrapping my head around how a certain line of code works. 我在围绕某些代码行的工作方式上遇到麻烦。 For some reason it's just not clicking. 由于某种原因,它只是没有单击。 This line of code is used generally with abstracting file handles in unix domain sockets. 这行代码通常与unix域套接字中的抽象文件句柄一起使用。

Context: 内容:

typedef struct myStruct {
    char charArray[10];
} myStruct; 

myStruct myStructure;
myStruct *ptrToStruct = &myStructure;

/* This should change myStructure.charAarray[0] to equal a */
*(ptrToStruct.charArray) = 'a'; 

I understand that an array is essentially a pointer that is pointing to the first index in the array but the pointer has no data ( charArray ). 我知道数组本质上是一个指向数组中第一个索引的指针,但该指针没有数据( charArray )。

The reason this is so hard for me to understand is because the ptrToStruct is trying to access the pointer's data member charArray but the pointer has no data member charArray and then it's dereferencing it. 这让我很难理解,原因是ptrToStruct试图访问指针的数据成员charArray但是指针没有数据成员charArray ,然后取消引用它。

Is this sort of like (*ptrToStruct).(*charArray) = 'a' ? 就像(*ptrToStruct).(*charArray) = 'a'吗? But the dereferencing operator is being factored out? 但是取消引用运算符被排除在外了吗? I apologize for being at all unclear. 很抱歉我不清楚。


UPDATE : The question has been answered. 更新 :该问题已得到解答。 I was misreading code, the code was actually *(myStructure.charArray) and that's how it was altering the first index of the array. *(myStructure.charArray)代码,代码实际上是*(myStructure.charArray) ,这就是它更改数组的第一个索引的方式。 I should have also figured this out because as Sid explained pointers do not have the . 我也应该弄清楚这一点,因为正如Sid解释的那样,指针没有. operator. 操作员。

ptrToStruct isn't a struct, so ptrToStruct不是结构,所以

ptrToStruct.charArray

should be 应该

(*ptrToStruct).charArray

or 要么

ptrToStruct->charArray

Then, yes, you can set the character using 然后,可以,您可以使用

*( ptrToStruct->charArray ) = 'a';

or 要么

( ptrToStruct->charArray )[0] = 'a';

This is no different than 这没有什么不同

char charArray[10];
*charArray = 'a';

and

char charArray[10];
charArray[0] = 'a';

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

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