简体   繁体   English

初始化结构指针-c

[英]initializing a structure pointer - c

Sorry if it is a too simple question. 抱歉,这是一个太简单的问题。 I was trying to compile some socket invoking code, and I had to use this 我试图编译一些套接字调用代码,所以我不得不使用它

SOCKADDR_IN * sin;
sin.sin_addr.s_addr    = htonl(INADDR_ANY);   

The problem is that I am told that I must initialize the pointer. 问题是,我被告知必须初始化指针。 (Is it necessary ?) Btw, how to initialize a structure pointer ? (是否有必要?)顺便说一句,如何初始化结构指针?

It is necessary that you allocate memory for a SOCKADDR_IN instance. 必须为SOCKADDR_IN实例分配内存。 You don't have to create a pointer though; 但是,您不必创建一个指针。 you could allocate it on the stack instead 您可以将其分配在堆栈上

SOCKADDR_IN sin;
sin.sin_addr.s_addr    = htonl(INADDR_ANY);

then use the address operator & if you want to pass sin to a function that expects a SOCKADDR_IN* 然后使用地址运算符&如果您想将sin传递给需要SOCKADDR_IN*的函数,

SOCKADDR_IN sin;
sin.sin_addr.s_addr    = htonl(INADDR_ANY);
....
function_using_socket_pointer(&sin);

Update: it seems you want to use a dynamically allocated pointer. 更新:似乎您想使用动态分配的指针。 You can do this using 您可以使用

SOCKADDR_IN* sin = malloc(sizeof(*sin));
if (sin == NULL) {
    /* insert oom handling here */
}
sin.sin_addr.s_addr    = htonl(INADDR_ANY);
....
free(sin);

You want to declare one on the stack instead of as a pointer. 您想在堆栈上声明一个而不是作为一个指针。 A pointer is just a memory address, not the actual instance of the object. 指针只是一个内存地址,而不是对象的实际实例。

Just change your code to 只需将代码更改为

SOCKADDR_IN sin;
sin.sin_addr.s_addr    = htonl(INADDR_ANY);   

And then when you need to use it, take the address of it like this: &sin 然后,当您需要使用它时,使用如下地址: &sin

Edit for original question answer 编辑原始问题答案

To initialise a pointer if you really want to would be to do this: 如果确实要初始化一个指针,可以这样做:

SOCKADDR_IN* sin = (SOCKASSR_IN*)malloc(sizeof(SOCKADDR_IN));
....use sin....
free(sin);

This will allocate you memory on the heap with the size being set to the size of the SOCKADDR_IN struct. 这将在堆上为您分配内存,大小设置为SOCKADDR_IN结构的大小。 But as said before, this is unnecessary and generally should be avoided unless you need to use this structure outside of the current stack frame (function). 但是如前所述,这是不必要的,通常应避免,除非您需要在当前堆栈框架(函数)之外使用此结构。

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

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