简体   繁体   English

Typedef结构导致程序崩溃

[英]Typedef struct causes program to crash

I'm trying to enqueue a struct array but it crashes whenever I try to insert information into it. 我正在尝试使结构数组入队,但是每当我尝试向其中插入信息时它就会崩溃。

The struct itself looks like this: 结构本身看起来像这样:

typedef struct {
    char first_name;
    char last_name;
    char pers_nbr;
} person;

While the function looks like this: 该函数如下所示:

void enqueue(person pers)
{
    strcpy(queue[tail].first_name, pers.first_name);
    strcpy(queue[tail].last_name, pers.last_name);
    strcpy(queue[tail].pers_nbr, pers.pers_nbr);

    tail = (tail+1) % QUEUE_MAX_SIZE;
    nbr_elem++;
}

I've been debugging and it crashes at the first strcpy and returns the error "Access violation reading location". 我一直在调试,它在第一个strcpy崩溃,并返回错误“访问冲突读取位置”。 The issue seems to be with the pers object. 问题似乎与pers对象有关。

Here's how I've been trying to insert data: 这是我一直尝试插入数据的方式:

person test;
test.first_name = "John";
test.last_name = "Doe";
test.pers_nbr = "A";
enqueue(test);

What causes this crash and how can I prevent it? 是什么原因导致此崩溃,如何预防?

When you declare a variable like 当你声明一个像

char first_name;

it means there is space for one character 这意味着一个字符有空间

you should instead use an array of characters to hold the string 你应该使用字符数组来保存字符串

char first_name[64];

and

person test;
test.first_name = "John";

is not the correct way to initialize a string or a struct, either do it in the declaration or manually strcpy in the string as u did previously: 不是初始化字符串或结构的正确方法,如在声明中进行操作或像以前一样手动对字符串进行strcpy:

person test = { "John", "Doe", "A" };

The char types in the struct should be char* in order to store strings, otherwise they just store a single character. 为了存储字符串,结构中的char类型应该为char *,否则它们仅存储单个字符。 Furthermore, space should be allocated for them. 此外,应为其分配空间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM