c - 如何创建结构体c的动态矩阵?

标签 c memory dynamic matrix

我在制作动态结构矩阵时遇到了一些麻烦。对于动态矩阵,我的意思不是固定数量的列或行。我有固定数量的列(26 个字母),但我希望每列中的行数发生变化。

这就是我到目前为止所做的......

struct cliente {
   char nome[9];
   struct cliente* next;
};

typedef struct cliente *ClienteSing;
typedef ClienteSing* Cliente[26];

//I'm allocating memory for the matrix. r is an array that tells me the number of lines for a column.
void initArrayCliente (Cliente a, int* r){
   int i=0;
   for(i=0;i<26;i++)
      a[i]=(ClienteSing) calloc (r[i],sizeof(struct cliente));
}

//I'm implementing a hash, so in case of collision, i make a linked list from a position in the matrix. This function puts a client i want to insert, in the correct position in case of collision.
void ultimoRamo (ClienteSing a, ClienteSing b){
   ClienteSing temp;
   temp=a;
   while (temp->next!=NULL)
      temp=temp->next;
   temp->next=b;
}

//I create a client b from a str that contains the client name. In case that the position in the matrix is set to null(doesn't have cliente) i insert b there. Otherwise, i will use the previous function to create a linked list from that position. indice is the position i want to insert in to. It's a value generated by my hash 
void insere(Cliente a, char* str, int indice){

   ClienteSing b;
   b= (ClienteSing) malloc (sizeof(struct cliente));
   strcpy (b->nome, str);
   b->next=NULL;

   if (a[str[0]-'A'][indice]==NULL)
   {
      a[str[0]-'A'][indice]=b;
      printf("Livre\n");
   }
   else {
      ultimoRamo(a[str[0]-'A'][indice],b);  
      printf("Colisão\n");
   }
}

我可以毫无问题地编译这个,它插入得很好并且不会给我任何段错误...但是当我打印矩阵中的内容时,它会给我垃圾...如果我打印同一个单元格在插入函数内,它可以毫无问题地打印...你能帮我找出我做错了什么吗?

最佳答案

您的打印代码错误:

for(z=0;z<26;z++)
    for(t=0;t<arrayCliente[z];t++)
        if(a[z][t].nome==NULL){printf("Fodeu-se");}
        else printf("%s",a[z][t].nome);

a[z][t].nomechar 数组,而不是指向 char 的指针。因此,只有当 a[z][t] 本身是 NULL 时,它才为 NULL,而且只是偶然,因为 nome 是该结构的第一个成员。

此外,您分配和操作结构数组,而不是结构指针数组。比较 a[str[0]-'A'][indice]==NULL 是没有意义的。

我建议你去掉指针,更重要的是去掉数组typedefs,这是一个非常令人困惑的 C 结构。然后使矩阵成为指向结构体指针数组的指针数组。

关于c - 如何创建结构体c的动态矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29155883/

相关文章:

c - win32在移植c代码时alarm,bzero,bcopy有什么替代方案

c - Raspberry PI、GPIO 带 SYSFS 的上拉/下拉电阻

java - ArrayList 的内存分配如何工作?

javascript - AngularJS 嵌套 ng-repeats 和嵌套绑定(bind)

最初未绘制组合框下拉列表

ios - 如何调试 NSZombies 和内存泄漏?

c++ - Dijkstra 算法 : memory consumption

c# - 这是使用 C# 动态的合理方式吗?

javascript - 如何保存 HTML 中的更改?

c - 我不断收到错误消息的此 c 代码中有什么错误?