我在我的程序中遇到了與我的display_matrix
函數有關的問題,並且我在運行程序時也遇到了分段錯誤,我不知道這是否與我無關destroy_memory函數還是什麼。我的程序讀入矩陣的維度,然後創建從1到100的隨機數並生成矩陣,然後顯示它,然後釋放分配的內存。我相信我的顯示功能,我必須使用嵌套for循環打印出的值。任何幫助表示感謝,並提前感謝您。下面是我現在的代碼以及我的程序的示例輸出。使用鏈接列表創建矩陣
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
typedef struct MatrixNode_{
int value;
struct MatrixNode_ *next_row;
struct MatrixNode_ *next_col;
}MatrixNode;
void create_linked_list_matrix(MatrixNode** head, const int rows, const int cols);
MatrixNode* create_node(void);
void display_matrix(MatrixNode* head);
void destroy_linked_list_matrix(MatrixNode** head);
int main (int argc, char *argv[]) {
if (argc < 3) {
exit(1);
}
srand(time(NULL));
const int rows = atoi(argv[1]);
const int cols = atoi(argv[2]);
MatrixNode* head_a = NULL;
printf("Matrix A\n");
create_linked_list_matrix(&head_a,rows,cols);
display_matrix(head_a);
destroy_linked_list_matrix(&head_a);
}
MatrixNode* create_node(void){
MatrixNode *temp = (MatrixNode *)malloc(sizeof(MatrixNode));
if(temp == NULL){
printf("Memory alloc error");
exit(1);
}
temp->next_col = NULL;
temp->next_row = NULL;
temp->value = rand() % 100 + 1;
return temp;
}
/*The MatrixNode double pointer will be NULL when first coming in,
make sure to allocate space For it and adjust your linked list of linked
list to start from 1 not 0. Next allocate a linked list of
MatrixNodes using the next row as the next node in the linked list.
You will need to create the linked list length up to the passed in rows value.
After the allocation of the rows linked list, we need to allocate a separate
linked list for each of the next_col MatrixNode pointers in the rows linked list.
To create the linked list for the columns create the linked list of MatrixNodes
using the next_col as the next node in the linked list. You will need to create
the linked list length up to the passed in cols value.
Use the create_node function to create nodes for your linked list.
*/
void create_linked_list_matrix(MatrixNode **head, const int rows, const int cols){
MatrixNode *tmpabove = NULL, *tmpleft = NULL, *tmpaboveleft = NULL, *newnode = NULL;
int i, y;
for(i = 0; i < rows; i++){
tmpleft = NULL;
for(y = 0; y < cols; y++){
newnode = create_node();
if(tmpabove != NULL) tmpabove->next_row = newnode;
if(tmpleft != NULL) tmpleft->next_col = newnode;
else{
tmpaboveleft = newnode;
tmpleft = newnode;
}
tmpabove = tmpabove->next_col;
tmpleft = tmpleft->next_col;
}
tmpabove = tmpaboveleft;
}}
void display_matrix(MatrixNode* head){
MatrixNode *temp = head;
while(temp != NULL){
printf("%d", temp->val);
temp = temp->next_col;
}
temp = temp->next_row;
}
輸出樣本:
./a.out 3 3
Matrix A
66 39 33
13 94 15
94 64 23
1)'MatrixNode *新=頭;':類型是不同的。 2)'new = create_node(); new = new-> next_row;':不形成鏈接。 – BLUEPIXY
您還沒有創建足夠的節點。在你的示例中,你將有三個矩陣節點,它們有指向下一行的指針和三個指向下一列的(不同的)矩陣節點。您應該有九個節點,每個節點有兩個鏈接,一個用於下一行,一個用於下一列。 – ianharris
是的,高爾基有道理,但我該怎麼做呢?我只需在for循環中添加new = new-> next_col和new = new-> next_row? – user3699735