全局初始化结构

时间:2015-05-19 07:09:27

标签: visual-c++ struct initialization global-variables

如何全局初始化struct sockaddr_in。第三个变量IN_ADDR sin_addr是一个嵌套结构。

struct sockaddr_in{
   short sin_family;
   unsigned short sin_port;
   IN_ADDR sin_addr;
   char sin_zero[8];
} addr;

struct in_addr {
   union {
      struct { u_char s_b1,s_b2,s_b3,s_b4; } S_un_b;
      struct { u_short s_w1,s_w2; } S_un_w;
      u_long S_addr;
   } S_un;
};

2 个答案:

答案 0 :(得分:0)

第1点

你无法初始化struct sockaddr_in本身。你需要有一个这种类型的变量,即你可以初始化的addr(如你的情况)。

第2点

您可以在大括号括起来的形式中使用inilitalizer列表来初始化全局变量。此外,您可以使用.identifier选项明确初始化成员。

假设IN_ADDR被定义为

typedef struct sockaddr_in IN_ADDR;

你可以写一些像

这样的东西
struct sockaddr_in{
   short sin_family;
   unsigned short sin_port;
   IN_ADDR sin_addr;
   char sin_zero[8];
} addr = {AF_INET, 2015, .sin_addr.S_un.S_addr = 1234567890, .sin_zero = {1,2,3,4,5,6,7}};

初始化addr

此处,.sin_addr.S_un.S_addr用于表示要初始化的特定变量。

答案 1 :(得分:0)

使用你的结构/联合定义......这是一个示例程序......

#include <stdio.h>

typedef unsigned char u_char;
typedef unsigned short u_short;
typedef unsigned long u_long;

typedef struct in_addr
{
        union
        {
                struct { u_char s_b1,s_b2,s_b3,s_b4; } S_un_b;
                struct { u_short s_w1,s_w2; } S_un_w;
                u_long S_addr;
        }S_un;
}IN_ADDR;

IN_ADDR u =  // ====> Either do something like this ...
{
        .S_un.S_un_b = {'a', 'b', 'c', 'd'}
        //.S_un.S_un_w = {1, 2},
        //.S_un.S_addr = 121212
};

struct sockaddr_in
{
        short sin_family;
        unsigned short sin_port;
        IN_ADDR sin_addr;
        char sin_zero[8];
}addr = { // ==============> Or do something like this.
                10,
                20,
                .sin_addr.S_un.S_addr=12345,
                "SOCKET"
        };


int main()
{
        printf("sin_family = %d\n", addr.sin_family);
        printf("sin_port = %d\n", addr.sin_port);
        printf("sin_addr.S_un.S_addr = %ld\n", addr.sin_addr.S_un.S_addr);
        printf("sin_zero = %s\n", addr.sin_zero);


        printf("%c %c %c %c\n", u.S_un.S_un_b.s_b1, u.S_un.S_un_b.s_b2, u.S_un.S_un_b.s_b3, u.S_un.S_un_b.s_b4);
        //printf("%d %d\n", u.S_un.S_un_w.s_w1, u.S_un.S_un_w.s_w2);
        //printf("%ld\n", u.S_un.S_addr);

        return 0;
}