0

配列のようにポインター「セル」にアクセスできないのはなぜですか? 適切なメモリを割り当てましたが、ここで配列のように機能しないのはなぜですか? 基本データ型のポインターの配列のように機能します。

#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#define MAX 10
struct node
{
    int e;
    struct node *next;
};  

typedef struct node *List;
typedef struct node *Position;

struct Hashtable
{
    int Tablesize;
    List Cells;
};

typedef struct Hashtable *HashT;

HashT Initialize(int SIZE,HashT H)
{   
    int i;
    H=(HashT)malloc(sizeof(struct Hashtable));
    if(H!=NULL)
    {
        H->Tablesize=SIZE;
        printf("\n\t%d",H->Tablesize);
        H->Cells=(List)malloc(sizeof(struct node)* H->Tablesize);

これからは配列のように振る舞うべきではありませんか?

        if(H->Cells!=NULL)
        {
            for(i=0;i<H->Tablesize;i++)

次の行はエラーをスローする行です

            { H->Cells[i]->next=NULL;
              H->Cells[i]->e=i;
                printf("\n %d",H->Cells[i]->e);
            }
         }
     }
     else printf("\nError!Out of Space");
}

int main()
{  
    HashT H;
    H=Initialize(10,H);
    return 0;
}

私が得るエラーはタイトルエラーのようです:invalid type argument of '->' (have 'struct node').

4

3 に答える 3

0

これは、typedef のないバージョンのプログラムです。読みやすいのはどっち?

#include <stdio.h>
#include <stdlib.h>

struct node {
    struct node *next;
    int e;
    };

struct Hashtable {
    unsigned Tablesize;
    struct node *Cells;
    };

struct Hashtable *Initialize(unsigned size)
{
    unsigned iii;
    struct Hashtable *hp;

    hp = malloc (sizeof *hp);
    if(!hp) {
        fprintf(stderr, "Error!Out of Space\n");
        return NULL;
        }

    hp->Cells = malloc(size * sizeof *hp->Cells );
    if(!hp->Cells) {
           hp->Tablesize = 0;
           return hp;
           }

    hp->Tablesize = size;
    fprintf(stderr, "\t%u\n", hp->Tablesize);
    for(iii=0; iii < hp->Tablesize; iii++) {
         hp->Cells[iii].next = NULL;
         hp->Cells[iii].e = iii;
         fprintf( stderr, " %u\n", hp->Cells[iii].e);
         }
    return hp;
 }

 int main()
 {
    struct Hashtable *hashtab;

     hashtab = Initialize(10);
     return 0;
 }

変更:

  • typedef を削除しました。彼らは混乱しているので
  • 不要で潜在的に危険な malloc() からのキャストを削除しました。
  • サイズを署名なしに変更しました。サイズが負になることはありません
  • 診断出力は stderr に送られる必要があります。
  • エラーケースを最初に実行し、エラーが発生した場合は関数から早期に戻ることで、いくつかのレベルのインデントを回避できます。
于 2013-10-26T15:56:12.917 に答える