c - C 中的空数组并返回指针

标签 c arrays

我对 C 编程非常陌生,我不确定是否创建一个函数来创建一个数组,并为该数组分配了空间,并让它返回一个指向该数组的指针。这是我到目前为止所拥有的: 编辑

struct Array {
    int* sort;
    int arraySize;
    int totalSize;
};


array* createarray(int elements)
{
    int arr[elements];
    int *p;
    int *p_array;
    p = &arr;
    p_array = (int *)malloc(sizeof(int)*elements);
    return p;    
}

这是创建空数组列表的正确方法吗?如果不请解释一下?

最佳答案

将您的工作拆分为单独的职能。不要强制转换 malloc。例如:

int* create_array(int elements)
{
    int* p = NULL;
    p = malloc(sizeof(int) * elements);
    if (!p) {
        fprintf(stderr, "Error: Could not allocate space for array\n");
        exit(EXIT_FAILURE);
    }
    return p;    
}

struct List* create_list(int max_elements) 
{
    struct List* l = NULL;
    l = malloc(sizeof(struct List));
    if (!l) {
        fprintf(stderr, "Error: Could not allocate space for list\n");
        exit(EXIT_FAILURE);
    }
    l->sortedList = create_array(max_elements);
    l->size = 0;
    l->maxSize = max_elements; 
    return l;
}

关于c - C 中的空数组并返回指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31394213/

相关文章:

c - return 使指针来自整数而不进行强制转换[默认启用]

javascript - 数组原型(prototype) toString() 与对象 toString()

javascript - 从函数 jquery 调用数组

php - 循环多维数组以输出 uniq 数字的列表

C 内联汇编标签问题

c - 通过宏过度使用进行结构初始化

c - C 中的 union 与结构

c - 微型 C 编译器链接我的程序集目标文件

python - 如何在Python中检测数组中的值是否在特定范围内并返回二进制数组?

javascript - 如何将预先生成的数组传递给 Angular 模板中的组件?