简体   繁体   English

为什么我在C中动态分配的struct数组不起作用?

[英]Why isn't my dynamically allocated struct array in C working?

I have been trying to create a dynamically allocated array of struct type label and have been failing miserably. 我一直在尝试创建一个动态分配的结构类型label数组,并且失败了。 In my .h file, I have: 在我的.h文件中,我有:

    typedef struct _label {
            char name[256];
            char type[256];
            int address;
} label;

and in my .c file, I have this at the top: 在我的.c文件中,该文件位于顶部:

    label* allLabels = (label*) malloc(sizeof(label) * 10); // line 10
    int arrayIndex = 0;

and finally, I have a function in the same .c file that is meant to add these struct objects to the array to be used by other methods in the file: 最后,我在同一个.c文件中具有一个函数,该函数旨在将这些struct对象添加到数组中,以供文件中的其他方法使用:

    void addLabel(char line[], char type[], int addr) {
            label database;
            database.name = line; // line 805
            database.type = type; // line 806
            database.address = addr;
            allLabels[arrayIndex] = database;
            arrayIndex++;
        }

Basically I just want to have a collection of accessible labels. 基本上,我只想拥有一组可访问的标签。 Can someone help me understand what I'm doing wrong? 有人可以帮助我了解我在做什么错吗?

I get these errors, and I haven't forgotten any of the necessary #include statements either: 我收到这些错误,并且我也没有忘记任何必要的#include语句:

formatBuilder.c:10:3: error: initializer element is not constant
formatBuilder.c: In function 'addLabel':
formatBuilder.c:805:18: error: incompatible types when assigning to type 'char[256]' from type 'char *'
formatBuilder.c:806.18: error: incompatible types when assigning to type 'char[256]' from type 'char *'

You can't assign to char arrays like that, you need one of the string operations, such as: 您不能像这样分配给char数组,需要字符串操作之一,例如:

strcpy (database.name, line);  // or "->" if database is pointer

(preferably checking the length beforehand to ensure no buffer overflow, or using a safer function depending on your needs). (最好事先检查长度,以确保没有缓冲区溢出,或者根据需要使用更安全的功能)。

It's also bad form to cast the return value from malloc in C since it can hide certain subtle errors. 在C语言中mallocmalloc返回值也是一种不好的形式,因为它可以隐藏某些细微的错误。 It's acceptable if your code has to also compile in C++ but you just need to ensure you have the correct prototype in scope. 如果您的代码也必须在C ++中进行编译,这是可以接受的,但是您只需要确保范围内的原型正确即可。


In terms of the initialisation error, I suspect that you have the declaration at file level (outside of any function). 关于初始化错误,我怀疑您在文件级别(任何函数之外)都具有声明。 This means you can't use a function call to initialise it since it has static storage duration and wants to be set before any code runs. 这意味着您不能使用函数调用对其进行初始化,因为它具有静态存储持续时间,并且希望在运行任何代码之前进行设置。

You can get around that problem thus: 您可以这样解决问题:

// At file level:

label* allLabels = NULL;

// In your function:

void addLabel(char line[], char type[], int addr) {
    if (allLabels == NULL) {
        allLabels = malloc (sizeof(label) * 10);
        if (allLabels == NULL) {
            // malloc failed, do something to recover.
        }
    }
    // And we don't need local storage here, hit the array directly.

    strcpy (allLabels[arrayIndex].name, line);
    strcpy (allLabels[arrayIndex].type, type);
    allLabels[arrayIndex].address = addr;
    arrayIndex++;
}

This uses a constant initialiser NULL to set the value and you then just need to ensure it's allocated before the first time you use it. 这使用常量初始化程序NULL设置值,然后您只需确保在第一次使用它之前就已对其进行了分配。

我建议使用memcpy

memcpy(&allLabels[arrayIndex], &database, sizeof(label));

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

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