0
void addWorkerToProject(Worker *worker, Project *project) {
    worker->projects =  malloc(sizeof (strlen(project)+1));
    worker->projects[worker->projectCount]->name =  project->name;
    worker->projectCount++;
}

    struct Worker

    char *name;
    Project **projects;
    int projectCount;

    struct Project

    char *name;
    Worker **workers;
    int workerCount;
    FeatureNode *features;

How do I make this function run correctly? It supposed to assign workers to project, but it fails to assign 2 projects to the same worker.

Let's say I have a worker named Sean and two projects name first and second. I need to attach them to Sean so for example when I print workers[i]->projects[j]->name they both needs to appear, when each iteration adds him 1 project. When I run it the first iteration is correct but the second one doesn't work.

2
  • 1
    Please post a Minimal, Reproducible Example and describe "run correctly" (for example, how the data should be set). Commented Mar 10, 2024 at 12:13
  • (strlen(project->name) + 1) * sizeof(Project*) makes no sense. Why do you want to multiply the string length with the size of a pointer (which will likely always be 8)? And if you want to copy a number of Project structures, you need a loop. Commented Mar 10, 2024 at 12:22

1 Answer 1

1

malloc(sizeof (strlen(project)+1)) will always return size of an integer. i.e.4 bytes/8 bytes based on your machine/os. What I felt you are trying to do is as below:

void addWorkerToProject(Worker *worker, Project *project) {
    worker->projects[worker->projectCount] =  malloc(sizeof(Project));
    worker->projects[worker->projectCount]->name = project->name;
    worker->projectCount++; 
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.