c - 使用 malloc 的多个数组

标签 c arrays data-structures struct

我正在初始化一个名为 Array 的结构,它由一个 Items 数组和一个用于跟踪 Items 数量的 int 组成。

  typedef struct anything{
    char text[MAXI];
    int any;
  }Item;

  typedef struct array{
    Item arr[0];
    int size;
  }Array;

为了初始化数组,我使用 malloc 并返回指针。

Array create(){
    Array *p1 = malloc(sizeof(Array));
    p1->size = 0;
    return *p1;
}

我遇到的问题是有些函数是为 2 个数组设计的,例如交集:

Array intersection(Array S,Array T){
    int i, j;
    Array I = create();
    for(i=0; i<(S.size); i++){
        for(j=0; j<(T.size); j++){
            if((compStructs(S.arr[i], T.arr[j])) == true)
                add(I, S.arr[i]);
        }
    }
    return I;
}

根据这段代码,如果我执行 create() 两次,我将丢失指向第一个数组的指针。我可以在主程序中做些什么来防止这种情况,或者我可以对当前函数进行哪些修改?

编辑:添加添加项目功能:

void add(Array S,Item x){

bool rep = false;
    int i = 0;
    for(i = 0; i<(S.size); i++){
        if(compStructs(x,S.arr[i]) == true)
            rep = true;
    }
    if(rep == false){
            Item *p2 = realloc(S.arr, sizeof(Item));
            *p2 = x;
            (S.size)++;
    }
    else
        printf("The item is already in the set.");

}

我的主要问题是我不确定如何调用将根据用户请求创建的两个单独的数组。该程序正在构建中,但目前看起来像这样:

#include "array.h"
Item x;

void arraymenu(){
    char inp;
    while((inp = getchar())!= '\n'){
        printf("a. To Create a new Array\n"
                "b. To Add a new Item\n"
                "c. To Remove an Item\n"
                "d. To Clear all contents of the Array\n"
                "e. To Get the size of the Array\n"
                "f. To Get a list of the number of elements of your choice\n"
                "g. To Check whether the array is empty\n"
                "h. To Get the union of two sets\n"
                "i. To Get the intersection of two sets\n"
                "j. To Get the difference of two sets\n"
                "k. To Check if a set is the subset of the other one\n"
                "l. To map a function to all Items of an Array\n"
                "m. To apply a function to all Items of an Array\n"
                "n. To store the Array in a File\n"
                "o. To load the Array from a File\n"   );

        switch(inp){
            case 'a' :  printf("Array A has been created.");
                        Array A = create();
                        break;

            case 'b' :  printf("Enter any integer, followed by any string.");
                        scanf("%d", &x.any);
                        scanf("%s", &x.text);
                        add(A, x);
                        break;

            case 'c' :  printf("Enter the integer and string you wish to remove ");
                        scanf("%d", &x.any);
                        scanf("%s", &x.text);
                        removee(A,x);
                        break;
        }
    }
}

最佳答案

基本上,您需要返回一个指针,而不是指向给定函数作用域的局部变量的解引用指针(顺便说一句,编译 return *ptr 应该给出警告编译时,添加 -Wall,不要忽略编译器告诉你的内容):

Array *create()
{
    Array *a_ptr = malloc(sizeof(*a_ptr));
    if (a_ptr == NULL) exit (EXIT_FAILURE);//failed to allocate memory
    a_ptr->size = 0;
    return a_ptr;
}

这样调用:

Array *S, *T;
S = create();
T = create();

现在您有 2 个数组可以使用了。请注意,您需要取消引用这些指针,或者始终对它们使用间接运算符:

(*S).size = 1;
//or
S->size += 123;

您可能还想将intersection更改为:

Array *intersection(Array *S,Array *T)
{
    int i, j;
    Array *I = create();
    for(i=0; i<(S->size); ++i)
    {
        for(j=0; j<(T->size); ++j)
            if(compStructs(S.arr[i], T.arr[j])) add(I, S.arr[i]);
        }
    }
    return I;
}

当然,一旦您使用完所有这些 Array 结构,您还必须 free() 它们。

compStructsadd 而言,我希望您也必须处理这些函数。当您使用它时,也许可以更改结构以更好地适合您使用它的方式:

typedef struct array
{
    Item *arr;
    size_t size;//size_t makes more sense here
  }Array;

当然,在释放内存时,这又需要做更多的工作,因此建议使用通用的释放函数:

void free_array(Array **a)
{//pointer to pointer
    while((*a)->size--) free((*a)->arr+(*a)->size);
    free(*a);
    *a = NULL;//NULL pointers are safer
}
//call like so:
free_array(&Array_ptr);//yes, address of pointer

并且 realloc 调用应该类似于:

realloc(a->arr, (a->size + 1)*sizeof(*(a->arr)));
a->size += 1;

关于c - 使用 malloc 的多个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20744417/

相关文章:

c - 如何使用 Doxygen 记录 errno 值?

c++ - Visual C++ 中的 _32_ 和 _64_ 等价物

java - if 语句打印出 'else' 部分,即使它是正确的

arrays - 如何删除 []byte 类型的字节

c - 在C中查找 "double free or corruption (out):"的原因

php - 如果某些 td 使用 jquery json 数据包含相同的 id,则 Rowspan

c++ - 总是用 g++ 获得有趣的段错误

java - 如何动态创建对象以添加到 Java 中的 ArrayList

java - 链接列表 add(i, x) 方法的代码审查

c++ - Pthreads- 1个锁,2个解锁