0

各構造体へのポインターと、構造体のポインターを指す void の 2 つの構造体を取得しまし**stackた。

私の問題はラインにあります

(*ptr2+*a)=(struct student *)malloc(sizeof(struct student));

*aスタッド登録が発生するたびに 1 ずつ増加する変数なので、同じアドレスに何度もメモリを割り当てません。

メニュー関数でアドレスを送信してからstud(&stud)、入力関数でアドレスを送信するため

*ptr2==stud 

したがって

stud[*a]== *(stud+*a)== *(*ptr2+*a)

なぜ間違っ(*ptr2+*a)ているの左側にあるのmallocですか?コードの一部

struct student
{
    char flag;
    char surname[256];
    int semester;
};

main()
{
    ...
    struct student *stud;
    menu(stack,stackcopy,reversedstack,&prof,&stud,stacksize,&head);
    ...
}

void menu(void **stack,void **stackcopy,void **reversed,struct professor **ptr1,struct student **ptr2,int size,int *head)
{
    ...
    input(stack,ptr1,ptr2,size,head,&a,&b);
    ...
}


int input(void **stack,struct professor **ptr1,struct student **ptr2,int size,int *head,int *a,int *b)
{
            ...
            done=Push(stack,head,(*(int *)ptr2+*a),size);
            (*ptr2+*a)=(struct student *)malloc(sizeof(struct student));
            stud_input(ptr2,a);
            ...
}
4

2 に答える 2

3

It's wrong because you need (roughly) a variable on the left side of the assignment, not a value. You can't write 1 = 2;, but you can write int a; a = 1;. By the same logic, you can't write &a = (void*)0;.

Dereferencing a pointer gives you a variable, so you can write struct student *z = &a; *z = b;.

If you want to write stud[*a] = malloc(...);, but you don't have stud, only ptr2, for which *ptr2 == stud holds, the correct way is, obviously,

(*ptr2)[*a] = malloc(...);

And (*ptr2)[*a] == *(*ptr2 + *a), so this would work as well:

*(*ptr2+*a) = malloc(sizeof(struct student));
于 2014-03-30T12:42:35.540 に答える
1

私の問題は次の行にあります

(*ptr2+*a)=(struct student *)malloc(sizeof(struct student));

malloc の結果をキャストしますか?

最初の試行で完全に間違っていたため、この回答を編集しました。私の頭の中には、あなたが実際に持っているよりも 1 つのレベルの間接性がありました。

malloc()多数のエントリが必要で、それを に割り当てるとします。つまり、実際studにある場所に書き込みます。stud

もしあなたがそれをするつもりならmain()、あなたはするだろう

struct student *stud = malloc(n * sizeof(*stud));

それぞれ

struct student *stud;
stud = malloc(n * sizeof(*stud));

nエントリー用のスペースが必要な場合。

呼び出された関数で同じことをしたい場合は、次のように置き換えstudます*ptr2

*ptr2 = malloc(n * sizeof(*stud));

ここでは、エントリを 1 つだけ割り当てたいようです。その後、あなたはただやります

*ptr2 = malloc(sizeof(*stud));

1 つのエントリ (必要に応じて) または適切に割り当てられたエントリの配列にアクセスするために使用できるポインタは1 つだけであることに注意してください。

それは本当ですが、

stud[*a]== *(stud+*a)== *(*ptr2+*a)

割り当てた数のエントリのみにアクセスできます。特に、1 つのエントリに必要なだけのスペースしか割り当てていない場合は、

stud[0] == *stud

どちらも であり、呼び出しstruct studentの結果を割り当てることはできません。malloc()

たとえば、

malloc(10 * sizeof(*stud))

studそれをまたは に割り当てると、*ptrさらにアクセスできます。

大藤(*ptr2+*a) == (stud + *a) == &stud[*a] == &(*ptr2)[*a]. しかし、コンパイラーが言うように、これは左辺値ではありません。そして、それが左辺値ではなかったとしても、この方法でアクセスすることは許可されていませんでした: while&stud[0]は正確にstud, が&stud[1]指している要素の後の要素をstud指しています.

そして、それが存在するのに十分な割り当てがない限り、このアクセスは読み取りには無効であり、書き込みにも無効です。2 番目の要素のアドレスは、常に最初の要素にsizeof(*stud)バイトを加えたアドレスであるため、変更できません。 .

あなたが何をしようとしているのか、私には完全にはわかりません。配列を間違った方法で割り当てたいと思います。

于 2014-03-30T12:47:12.710 に答える