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
...