简体   繁体   English

C ++ Struct指针问题

[英]C++ Struct pointer question

This is probably simple, but im trying to try and understand pointers better. 这可能很简单,但我试图更好地尝试和理解指针。 Lets say I have a struct 可以说我有一个结构

struct Person{
  char Name[20];
  char ID[15];
  char Address[50];
  char Number[15];
};

and lets say I have a bunch of these stored in memory like one after the other. 并且假设我有一堆这样的存储在内存中,就像一个接一个。 so now i declare a new pointer to the struct. 所以现在我声明一个指向结构的新指针。

struct Person *ptr;

Will this Pointer start at the FIRST entry? 这个指针会从第一个条目开始吗? (aka the first "Name") and when I iterate it (aka ptr++) will it go to the next STRUCT or the next "entry" aka like name-->ID--->Address (又名第一个“名称”),当我迭代它(又名ptr ++)时,它会转到下一个STRUCT或下一个“条目”,也就像名称 - > ID --->地址

So lets say Im on the first entry for example and the data is: 因此,我想在第一个条目上说Im,数据是:

Jason Adams
111222333
111 Fake Drive
55555551000

and the second entry is 第二个条目是

Matt Johns
111555333
555 Derp lane
1000022434

now I iterate the ptr (ptr++) will the ptr point to second struct (the one with matt johns) or will it point to Jason Adams "ID" 现在我迭代ptr(ptr ++)将ptr指向第二个结构(具有matt johns的结构)或者它将指向Jason Adams“ID”

I hope this makes sense? 我希望这是有道理的?

It will point to the second struct. 它将指向第二个结构。 The pointer will be advanced by sizeof(Person) . 指针将由sizeof(Person)提前。

As John mentioned, it will be advanced by the size of itself - aka sizeof(Person). 正如约翰所提到的那样,它将以其自身的大小 - 即sizeof(人物)来提升。

Pointer manipulation is fun however, and you can do things like cast the pointer to a different type. 然而,指针操作很有趣,你可以做一些事情,比如将指针转换为不同的类型。 Once you do that, pointer arithmetic will advance by the underlying size of the type. 一旦这样做,指针算术将按类型的基础大小前进。 Commonly you'll see pointers casted to (byte *) or (unsigned char *) to allow individual byte access to the underlying data. 通常,您会看到指向(byte *)或(unsigned char *)的指针,以允许单个字节访问底层数据。

First of all, you must allocate memory for your pointer ptr before using it. 首先,您必须在使用之前为指针ptr分配内存。

auto_ptr<Person> ptr(new Person); //auto_ptr for automatic freeing

After that, you can try below code. 之后,您可以尝试下面的代码。

strcpy(ptr->ID, "100"); //For illustraction
int offset = ptr->ID - ptr->Name; //Get offset of ID member
char *pID = ((char *)ptr.get())+ offset;
//Typecast to char pointer and increment by offset to get to ID field
cout<<pID; //Now pId can be used to access ID.

You asked how to access ID attribute by incrementing ptr. 您询问了如何通过递增ptr来访问ID属性。

As shown above, you can access ID member of structure. 如上图所示,您可以访问结构的ID成员。

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

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