c - 错误: misuse of undefined type 'struct IntArray'

标签 c struct segmentation-fault malloc modularization

我想编写这个程序,并将其放在一个名为 intarray.c 的文件中:

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

struct IntArray
{
    int length;
    int *array;
};

struct IntArray erzeugeArr(int length)
{
    struct IntArray erzeugt = {length, (int *)malloc(sizeof(int)*length)};
    return erzeugt;
}

这在测试主要中:

struct IntArray *string;
string = &(erzeugeArr(5));

现在,我得到的是这样的:

Misuse of undefined type "struct IntArray"

因为最后一位string = ...。查了很多资料,还是没明白问题所在!如果我这样做:

void erzeugeArr(struct IntArray *erzeuge, int length)
{
    struct IntArray erzeugt = {length, (int *)malloc(sizeof(int)*length)};
    erzeuge = &erzeugt;
}

struct IntArray *string;
erzeugeArr(string, 5);

,然后我可以编译我的程序,但是在启动它时,我遇到了段错误,我认为这是因为 main 无法访问 erzeugt

最佳答案

我猜你正在返回本地(结构)变量的地址,当你稍后尝试使用它时,会给你一个段错误(尝试访问无效地址)。

您可以在函数中动态分配结构并返回它。

        struct IntArray* erzeugeArr(int length)
        {
            struct IntArray *erzeugt=(struct IntArray*)malloc(sizeof(struct IntArray*));
            erzeugt->array = (int*) malloc(sizeof (int)*length);
            return erzeugt;
        }

        int main()
        {
            struct IntArray *str;
            str=erzeugeArr(10);
            //use str for processing
        }

关于c - 错误: misuse of undefined type 'struct IntArray' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16751120/

相关文章:

c - C中的结构类型转换

c - 在 C 中删除数组中的重复项并将第一个匹配项插入到新数组中

c - 在portaudio中打开原始数据流(例如tcpdump)

C - 限制结构范围

c++ - 到达主程序之前出现段错误 - C++

c - 错误: lvalue required as increment operand

C++指针疑惑

c++ - 迭代结构列表

c - 读取位置 0x003134d4 访问冲突

c++ - 将字符串分配给 stack.top() 时出现段错误