简体   繁体   中英

Modifying a structure passed as pointer in C

I'm a noob student trying to write a program that uses binary search tree to organize the workers of a company. My teacher told me if I want to be able to create a new instance of the Worker structure, i can use malloc with the structure, which will return pointer to a new struct every time it's used, then i can edit the details of that new struct from another function. But how can i do it? No matter what i do it gets so complicated and i can't do it. Here's the code i've been able to write this part of the code, just to test if i can create and edit a new structure. The main thing i ask is, how can i edit the newly created structure?

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

struct btnode
{
    int value = 5;
    struct btnode *l;
    struct btnode *r;
};

int test(int *p)
{

    printf("%d", &p->value);
}

int main()
{
    int *asdf = (int *)malloc(sizeof(struct btnode));

    test(asdf);
}

Here is a mod of your program which allocates memory for one struct , fills in values for its members, and calls test() to print one member.

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

struct btnode
{
    int value;
    struct btnode *l;
    struct btnode *r;
};

void test(struct btnode *p)
{
    printf("%d", p->value);
}

int main(void)
{
    struct btnode *asdf = malloc(sizeof *asdf);
    if(asdf != NULL) {
        asdf->value = 5;
        asdf->l = NULL;
        asdf->r = NULL;
        test(asdf);
        free(asdf);
    }
    return 0;
}

There are a number of small changes to detail too, I leave you to spot the differences.

First of all there are some mistakes in the code.
1) You can not assign values in the structure.
2) When you are making a pointer for the structure you need pointer of the structure not of the int (does not matter what you want from the inside of the structure)

This is the modified code which runs perfactly

#include<stdio.h>

struct btnode
{
    int value;
    struct btnode *l;
    struct btnode *r;
};

int test(struct btnode *p)
{

    printf("%d", p->value);
}

int main()
{
    struct btnode *asdf = (struct btnode*)malloc(sizeof(struct btnode));
    asdf->value = 5;
    test(asdf);
}

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