开发者

Why do I get a seg fault? I want to put a char array pointer inside a struct

consider the fallowing code:

typedef struct port * pport;

struct port
{
  int a;
  int b;
  pport next;
  pport prev;
  char * port;
};

void addNewport(pport head)
{
  pport 开发者_高级运维newPort = (pport)malloc(sizeof(pport*));
  newPort->prev=temp;
  head->next=newPort;
}

int main()
{
  pport head = (pport)malloc(sizeof(pport*));
  addNewport(head);
}

This will result in seg fault if try to add a new port via a subroutine, but if I perform it the main, no seg fault will appear. Why is that?


Replace

 malloc(sizeof(pport*))

with

 malloc(sizeof(struct port))

because you don't want to allocate memory for a pointer, rather for the struct.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜