我对 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/