错误的程序与结构-segmentation故障 [英] Error in the program with structures -segmentation fault

查看:207
本文介绍了错误的程序与结构-segmentation故障的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    #include <stdio.h>

    struct p

    {
        char *name;
        struct p *next;
    };

    struct p *ptrary[10];

    int main()
    {
        struct p p, q;
        p.name = "xyz";
        p.next = NULL;
        ptrary[0] = &p;
        strcpy(q.name, p.name);
        ptrary[1] = &q;
        printf("%s\n", ptrary[1]->name);
        return 0;
    }

该计划是给在执行segmention故障。
什么是错在这里?我需要为ptrary分配内存?

The program is giving segmention fault on execution. What is wrong here? Do I need to allocate memory for ptrary?

推荐答案

您将使用它之前分配一些内存。

You will have to allocate some memory before using it.

q.name = malloc(10);
strcpy(q.name, p.name);

编辑:正确地开卷指针移出,的sizeof 字符将始终为1。因此,从<$删除C $ C>的malloc 。

As correctly pointer out by unwind, sizeof char will be always 1. Hence removing from malloc.

这篇关于错误的程序与结构-segmentation故障的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆