为什么要停止工作"在c中使用结构时出错信息?

时间:2016-07-01 12:42:00

标签: c

我需要了解为什么要提供此错误消息"停止工作"。这是我的代码。

#include <stdio.h>

struct student{
    int id;
    char name[20];
    char *title;
};

int main()
{
    struct student *st;
    st->id = 23;
    //st->name = "shaib";
    st->title = "title";

    printf ("%d", st->id);
    printf ("%s", st->title);

    return 0;
}

4 个答案:

答案 0 :(得分:4)

您定义了一个指针,但它不是init,因此Undefined Behavior

您可以使用malloc函数在堆内存中创建空间。

int main()
{
    struct student *st = malloc(sizeof(struct student));

    if ( st != NULL)
    { 
       st->id = 23;
       ..
    }
    else
    {
       fprintf(stderr, "No space for variable\n");
    }

    free(st);
    return 0;
}

如您所见,每次使用malloc分配内存时,您都要负责free。否则你有memory leak

第二个问题是

 st->name = "shaib";

不是用C-String填充数组的方式。

您可以通过以下方式实现:

 strcpy(st->name, "shaib");

答案 1 :(得分:3)

因此,您需要为新结构分配一些内存:

1)添加#include以便......

2)替换malloc()

的struct声明

提示:使用\ t和\ n

为打印输出使用更好的格式

这是工作代码:

#include <stdio.h>
#include <stdlib.h>

struct student{
    int id;
    char name[20];
    char *title;
};

int main()
{
    struct student *st = malloc(sizeof (struct student));
    st->id = 23;
    //st->name = "shaib";
    st->title = "title";

    printf ("%d\t", st->id);
    printf ("%s\n", st->title);

   return 0;
}

答案 2 :(得分:2)

您正在创建指向学生结构的指针,但您并未将其设置为指向任何内容。

您需要先为st(学生结构)分配内存,然后才能使用它。

答案 3 :(得分:2)

您没有为st分配内存。

你可以这样做:st = malloc(sizeof (student));