为什么这个Struct的成员没有打印出来(C编程)

时间:2013-03-17 17:30:04

标签: c list struct linked-list structure

在'root'指向的'netAddr'下面的代码中的

打印put但不是'指针指向的'maskAddr'。在此先感谢,只作为最后的手段。 'netAddr'的值打印掉,但'指针'指向的任何内容都没有。

struct RouteInfo
{
unsigned long netAddr;
unsigned long gateAddr;
unsigned long maskAddr;
char ifName[IF_NAMESIZE];
int metric;
int ttl;
    struct RouteInfo *next;
};

   struct RouteInfo *root; /* This will be the unchanging first node */

    /* This will point to each node as it traverses the list */
    struct RouteInfo *pointer;

    //allocating space for the root
    root = malloc(sizeof(struct RouteInfo));
    root->next = 0;
    root->netAddr = 19216811;

    //Point to 1st Item
    pointer = root;

    /* Creates a node at the end of the list */
    pointer->next = malloc( sizeof(struct RouteInfo) );
    pointer = pointer->next;
    pointer->maskAddr = 25525500;

    pointer->next = malloc( sizeof(struct RouteInfo) );
    pointer = pointer->next;
    pointer->gateAddr = 19216810;

    pointer->next = malloc( sizeof(struct RouteInfo) );
    pointer = pointer->next;
    strcpy(pointer->ifName, "eth1");

    pointer->next = malloc( sizeof(struct RouteInfo) );
    pointer = pointer->next;
    pointer->metric = 16;

    pointer->next = malloc( sizeof(struct RouteInfo) );
    pointer = pointer->next;
    pointer->ttl = 30;

    //marking the last as NULL
    pointer->next = 0;

    //Pointer points to root again
    pointer = root;
        printf("%lu%lu \t",root->netAddr, pointer->maskAddr);

3 个答案:

答案 0 :(得分:2)

您永远不会初始化root->maskAddr

答案 1 :(得分:2)

实际上您没有分配到root->maskAddr = ;

之后:

root = malloc(sizeof(struct RouteInfo));
root->next = 0;
root->netAddr = 19216811;

添加:

root->maskAddr = 25525555;   

及其工作:

:~$ ./a.out 
19216811 25525555 

您可以在此处找到您的工作代码:Codepad

答案 2 :(得分:1)

正如NPE所说,你从不重视root->maskAddr。那么也许你的意思是这个?

printf("%lu%lu \t",root->netAddr, pointer->next->maskAddr);