简体   繁体   English

指向 struct 的指针,这甚至是指向 struct 的指针吗?

[英]Pointer to struct ,is this even a pointer to struct?

I have a struct and it has variables in it.我有一个结构体,里面有变量。 Now I need to allocate memory dynamically, so initially I use现在我需要动态分配内存,所以最初我使用

Struct struct-name *a =Null; 

Latter on , I will allocate memory to it using malloc ,then I use稍后,我使用malloc为其分配内存,然后使用

a[0].variableA=allocate , a[0].variableB=allocate.

My question is , is this even a pointer to struct, because no where I give the address of struct .我的问题是,这甚至是指向 struct 的指针,因为我没有给出 struct 的地址。 And moreover this technique works , how does it know the address of struct .而且这种技术是有效的,它是如何知道 struct 的地址的。 When I'm not explicitly giving address of struct using '&'.当我没有使用“&”明确给出结构的地址时。 I know this might be silly but I got confused .Thanks .我知道这可能很愚蠢,但我很困惑。谢谢。

Struct st
{
 int a ;
int b;
}
Struct a *ptr=NULL;

In main在主要

    ptr=malloc(sizeof(struct st)*2);
    //Assume array of size 2 is created 
Now I can use 
    ptr[0].a=10;

How can I use even without explicitly giving address of struct to it.即使没有明确给出结构地址,我如何使用它。

The thing is you are not getting how malloc works.问题是您没有了解malloc工作方式。 (You mentioned I will allocate memory to it using malloc ) (您提到我将使用 malloc 为其分配内存

struct struct_name *a = NULL;
a = malloc(sizeof *a);
...

This computes the number of bytes that a struct struct_name occupy in memory, then requests that many bytes from malloc and assigns the result (ie, the starting address of the memory chunk that was just created using malloc ) to a pointer named a .这将计算struct struct_name在内存中占用的字节数,然后从malloc请求那么多字节并将结果(即,刚刚使用malloc创建的内存块起始地址)分配给名为a的指针。 That is the whole story.这就是整个故事。

Now you will access it after making it sure that it didn't return NULL .现在您将在确保它没有返回NULL后访问它。 No need to apply & address of to any struct struct_name variable instance.无需对任何struct struct_name变量实例应用&地址。

In your case, ptr is used to access the different struct instance allocated dynamically - where is the address?在您的情况下, ptr用于访问动态分配的不同结构实例 - 地址在哪里? The address pointing to the first instance is contained in ptr .指向第一个实例的地址包含在ptr Then you used ptr[0] or ptr[1] to get to that structure instance.然后您使用ptr[0]ptr[1]来访问该结构实例。 And then you accessed it.然后你访问了它。

And yes ptr is a pointer to struct.是的ptr是指向结构的指针。

One extra thing:-额外的一件事:-

malloc may not be able to service the request, it may return a null pointer. malloc可能无法为请求提供服务,它可能会返回空指针。 It is good to check for this to prevent later attempts to dereference the null pointer.最好对此进行检查以防止以后尝试取消引用空指针。 If you dereference a NULL pointer then it's undefined behavior.如果您取消引用 NULL 指针,则它是未定义的行为。

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

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