为什么我会出现段错误?我想将 char 数组指针放入结构中
考虑以下代码:
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);
}
如果尝试通过子例程添加新端口,这将导致段错误,但如果我在主程序中执行它,则不会出现段错误。这是为什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
替换
为,
因为您不想为指针分配内存,而是为结构分配内存。
Replace
with
because you don't want to allocate memory for a pointer, rather for the struct.