簡體   English   中英

將結構的地址分配給C中的其他結構

[英]Assign address of struct to other struct in C

我想找到鏈接列表中的第一個。 我有個主意。

我將在struct中使用第一個地址。 我無法創建first或somemockup結構,因為我將多次使用此函數。

這些是我的結構:

typedef struct user user;
typedef struct message message;
struct message
{
    int id;
    int user;
    message *next;
    message *firstm;
};
struct user
{
    char name[10];
    int id;
    message *messages;
    user *next;
};

我添加用戶和ID。 沒關系。 我想添加這樣的用戶消息(不是二維數組或類似的東西)

我會這樣說:

firstme = &(temp->messages->firstm);
for (; temp->messages->next != NULL; temp->messages = temp->messages->next){}
temp->messages->firstm = firstme;
temp->messages->next = NULL;

沒關系。 我采用了第一個消息結構。

但是在那之后我想用它,因為我想全部打印。

for (temp->messages = (temp->messages->firstm); temp->messages->next != NULL; temp->messages = temp->messages->next){}

但這是行不通的。

&(temp->messages) = *(temp->messages->firstm) //<- that doesn't work too :(
(temp->messages) = *(temp->messages->firstm) //<- that doesn't work too :(

謝謝您的幫助 :)

您的類型不匹配。 您取消了temp->messages->firstm引用,因此它的類型為struct message。 messages是指向結構消息的指針類型, &(temp->messages)也是指針(但是指向指針的指針)。

將所有特殊操作數排除在遇到麻煩的行之外。

我認為這就是您要實現的目標(您可以在此處檢查它是否有效,您只需要一個C99編譯器):

#include <stdio.h>

typedef struct user user;
typedef struct message message;
struct message
{
    int id;
    int user;
    message *next;
    message *firstm;
};

struct user
{
    char name[10];
    int id;
    message *messages;
    user *next;
};

int main(void) {
    //initialize somme dummy structures
    user users[4] = {
        {.name = {0} }
    };
    message msgs[4] = {{0}};

    for (int i = 0; i < 4; i++) {
        msgs[i].firstm = &msgs[0];
        msgs[i].next = &msgs[i+1];
        msgs[i].id = i;
        users[i].messages = &msgs[0];
        users[i].next = &users[i+1];
    }
    msgs[4].next = NULL;
    users[4].next = NULL;

    //iterate through messages in first user and print ids
    user *temp = &users[0];
    for (message *firstme = temp->messages->firstm;
            firstme->next != NULL;
            firstme = firstme->next) {
        printf("%d \n", firstme->id );
    }

    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM