1

構造体の配列があり、各構造体は要素のリストとして機能します。各構造体に複数のオブジェクトを追加する必要があり、追加機能が正しく機能していません。

これは構造です:

typedef struct object book, *list;
struct object{
int type;
int quantity;
list next;
};

これは、配列と main() 関数にあるものを定義する方法です。

row_n=4 //fixed just for now
cols_n=3

product **t;

t= (product **)calloc(row_n, sizeof(product *));  // array of row pointers 
for (int i= 0; i<n; i++) {
t[i]= (product *)calloc(cols_n, sizeof(product));  // array of cols prod structs 
}

t[1][1].type= 5; //only for testing
t[1][1].quantity= 15; //only for testing
list_all(t,row_n,col_n); //list all elements inside each array, its working as intended
insert(t, 3, 6); //Trying to insert more books
insert(t, 6, 10);
insert(t, 9, 50);

これは list_all 関数です:

void list_all(product **t , int size_n , int size_m)
{
int i,j;
product *p;

for(i=0;i<size_n;i++){
    printf("--- row: ---: %d\n", i+1);
    for(j=0;j<size_m;j++){
        printf("--- col: ---: %d\n",j+1);
        p= &t[i][j];
        do {
            printf("Book Type:%d Amount:%d\n", p->type, p->quantity);
            p= p->next;
        } while (p!=NULL);
    }
  }
}

これは私の問題が実際に存在する場所です。この挿入機能を修正する必要があります。

void insert(product **t, int id, int quantity)
{
product *p, *aux = NULL;
p=&t[0][0]; //doing it only in one position to test
if((aux = malloc(sizeof(product))) == NULL)
    printf("Memory error\n");
else
{
    aux->type=id;
    aux->quantity=quantity;
    p->next = p; }
p = aux;
}

ブックの削除機能も必要ですが、まずこの問題を解決したいと思います。アドバイスありがとう。

4

2 に答える 2

0

エラーメッセージは何ですか?

あなたのコードで:

p->next = p;

次のようになります。

aux->next = p;

このようにして、製品をリストの先頭として挿入します。

于 2013-06-01T23:19:09.263 に答える
0

私が見る2つの問題は

p->next = p; -> aux->next = p;

    //if
    p=&t[0][0];

    then 

    at the end 

    t[0][0] = p;

t[0][0] がリストの先頭を指すのではなく、以前のポインターを指していると思うので、追加ノードは表示されません

于 2013-06-02T07:42:10.520 に答える