简体   繁体   中英

Assign address of struct to other struct in C

I want to find the first of the linked list. And i have an idea.

I will took the first address in struct. I can't create first or somemockup struct because i will use this function several times.

These are my structs:

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;
};

I add users and ids. Its ok. I want to add messages of user like this (not 2d array or something like that)

And i will assing something like that:

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

It is ok. I took the adress of first message struct.

But after that i want to use it in for because i want to printf all.

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

But that doesn't work.

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

Thank you for your help :)

You have a mismatch of types. You dereferenced temp->messages->firstm so it's of type struct message. messages is a pointer type to a struct message, and so is &(temp->messages) a pointer (but a pointer to a pointer).

Leave all the special operands out of the line you're having trouble with.

I think that is what you are trying to achieve (you can check here that it works, you just need a C99 compiler):

#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM