strtrs
strtrs

Reputation: 1

Dynamic memory allocation in c arrays of structs

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.

Upvotes: 0

Views: 77

Answers (1)

Amit
Amit

Reputation: 11

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

Upvotes: 1

Related Questions