如何创建结构c的动态矩阵?
我在制作结构的动态矩阵时遇到了一些麻烦。对于动态矩阵,我的意思不是固定数量的列或行。我有固定数量的列(字母表中的26个字母),但我希望每列的行数都有所改变 这就是我到目前为止所做的如何创建结构c的动态矩阵?,c,memory,dynamic,matrix,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
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");
}
}
struct客户端{
char-nome[9];
struct cliente*next;
};
typedef struct cliente*客户端;
typedef clientsing*客户[26];
//我正在为矩阵分配内存。r是一个数组,它告诉我一列的行数。
void initarrayclient(客户a,int*r){
int i=0;
对于(i=0;i您的打印代码错误:
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);
for(z=0;zSome risk business:您不检查str[0]是否确实是大写字母。您也不检查strlen(str)nome
。将打印函数的代码张贴出来,问题可能隐藏在那里。@chqrlie我的str大小都是6。例如,它的格式是AA111。我在这个代码之外检查:)这是我用来打印的代码,正如我所说的,我没有任何分段错误,即使在打印过程中也是如此。它只是打印垃圾。你假设str
总是6
,并且以大写字母开头,但是让你的代码对可能早晚发生的错误输入具有弹性。下一个程序员将不知道假设是什么你所做的一切。你甚至可能成为下一个程序员……我是舒尔100%的朋友:)我阅读并验证单词。我将字母转换为大写,只有当它们是这种格式时,我才让它们传递给此函数。如果它们不遵守此规则,则会被程序删除:)然后在此函数之前写一条明确的注释,解释为什么不检查参数的合理性。这样,读者(和潜在的维护人员)会知道的。所以删除typedef,只做一个ClientSing。然后做ClientSing**a;Malloc列数,每个c Malloc行数?就是这样吗?做a
一个指向struct ciente
结构的指针数组。struct cliente*a[26];
其中a[i] =calloc(r[i],sizeof(struct cliente*))
对于一个严格一致的程序,您应该将伪矩阵中的每个指针初始化为NULL
,因为NULL指针不一定都是零位。实际上,我从未遇到过一个实际的CPU,其中所有的零位都不是NULL
指针。但是有人可能有一个备用的DS9K模拟器来验证我的意思是。我会试试看。我会让你知道进展的。