Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,851 questions

51,772 answers

573 users

How to allocate memory for array of structs in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct  {
    char name[16];
    int age;
} worker;

#define SIZE 3

int main()
{
    worker *warr[SIZE];
    char s[2];

    for (int i = 0; i <= SIZE; ++i) {
        warr[i] = malloc(sizeof(worker));
        sprintf(s, "%d", i);
        strcat(strcpy(warr[i]->name, "Dana-"), s);
        warr[i]->age = 40 + i;
    }

    for (int i = 0; i <= SIZE; ++i) {
        printf("name: %s : age: %d\n", warr[i]->name, warr[i]->age);
    }

    for (int i = 0; i <= SIZE; ++i) {
        free(warr[i]);
    }

    return 0;
}



/*
run:

name: Dana-0 : age: 40
name: Dana-1 : age: 41
name: Dana-2 : age: 42
name: Dana-3 : age: 43

*/

 



answered May 4, 2021 by avibootz

Related questions

1 answer 179 views
1 answer 176 views
176 views asked Jul 11, 2019 by avibootz
1 answer 132 views
132 views asked May 4, 2021 by avibootz
1 answer 188 views
2 answers 257 views
1 answer 160 views
160 views asked Jul 10, 2015 by avibootz
...