实例化struct并分配字符串但字符串打印空行?

时间:2017-01-24 19:15:58

标签: c struct

我是C的新手,我试图实例化一个结构,但我没有得到任何我想要的字符串。我的结构非常简单,字符串在开头正确打印,直到我在结构中分配最后一个值。我究竟做错了什么?我需要分配更多空间吗?

这是我的终端中打印的内容

before local time is set: node->ip is 127.123.456.789
after local_time is set: node->ip is

如您所见,设置本地时间后,字符串显示为空白。我做错了什么?

#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct node {
  char *ip;
  short port;
  int heartbeat;
  int local_time;
};

typedef struct node node;

int main(int argc, char **argv) {

  node *node = malloc(sizeof(node));

  node->ip = malloc(INET_ADDRSTRLEN);
  memset(node->ip, '\0', INET_ADDRSTRLEN);    
  strcpy(node->ip, "127.123.456.789");

  node->port = 22;
  node->heartbeat = 12;

  printf("before local time is set: node->ip is %s\n", node->ip);
  node->local_time = 11;
  printf("after local_time is set: node->ip is %s\n", node->ip);

  return 0;
}

1 个答案:

答案 0 :(得分:1)

你所拥有的甚至不应该编译: node *node = malloc(sizeof(node));您不能拥有与结构名称相同的变量。

如果您将其更改为node *n = (node*)malloc(sizeof(node));并更改变量&#39;节点&#39;到了&#39; n&#39;,它运作正常。