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 dynamically allocate two structs with one malloc in C

2 Answers

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

typedef struct {
    int n;
    char ch;
} StructA;

typedef struct {
    float f;
    double d;
} StructB;

int main(void) {

    StructA* sa;
    StructB* sb;

    sa = malloc(sizeof(StructA) + sizeof(StructB));
    sb = (StructB *)&sa[1];

    sa->n = 639;
    sa->ch = 'z';

    sb->f = 3.14f;
    sb->d = 263745.8312;

    printf("%d %c %f %lf", sa->n, sa->ch, sb->f, sb->d);

    free(sa);

    return 0;
}




/*
run:

639 z 3.140000 263745.831200

*/

 



answered Feb 18, 2023 by avibootz
edited Feb 19, 2023 by avibootz
0 votes
#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int n;
    char ch;
} StructA;

typedef struct {
    float f;
    double d;
} StructB;

typedef struct {
    StructA;
    StructB;
} StructAB;

int main(void) {

    StructAB* sab;

    sab = malloc(sizeof(StructAB));

    sab->n = 639;
    sab->ch = 'z';

    sab->f = 3.14f;
    sab->d = 263745.8312;

    printf("%d %c %f %lf", sab->n, sab->ch, sab->f, sab->d);

    free(sab);

    return 0;
}




/*
run:

639 z 3.140000 263745.831200

*/

 



answered Feb 19, 2023 by avibootz

Related questions

2 answers 170 views
2 answers 173 views
1 answer 61 views
1 answer 135 views
135 views asked Dec 28, 2020 by avibootz
1 answer 157 views
...