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

时间:2015-03-19 22:05:51

标签: 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");
   }
}

我可以编译它没有任何问题,它插入良好,并没有给我任何分段错误...但是当我打印我在矩阵中的东西,它给我垃圾...如果我打印相同的细胞在插入功能中,它可以打印没有问题......你能帮我弄清楚我做错了吗?

1 个答案:

答案 0 :(得分:0)

您的打印代码有误:

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的指针。因此,NULL只有a[z][t]本身NULL,并且只是偶然,因为nome是此结构的第一个成员。

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

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