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 write a function that creates a dynamic array in different types with C

1 Answer

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

#define LEN 10

typedef unsigned int u32;

#define DYARRAY_CREATE(length, type) \
    _dyarray_create(length, sizeof(type))

void* _dyarray_create(u32 length, u32 typesize) {
    u32 array_size = length * typesize;
    u32* new_array = malloc(array_size);

    memset(new_array, 0, array_size);

    return (void*)(new_array);
}

int main(void)
{
    int* p = DYARRAY_CREATE(LEN, int);
    for (int i = 0; i < 10; i++) {
        p[i] = i * 10;
        printf("%3d", p[i]);
    }
    free(p);

    printf("\n");

    float* f = DYARRAY_CREATE(LEN, float);
    for (int i = 0; i < 10; i++) {
        f[i] = i * 3.14;
        printf("%6.2f", f[i]);
    }
    free(f);

    printf("\n");

    double* d = DYARRAY_CREATE(LEN, double);
    for (int i = 0; i < 10; i++) {
        d[i] = i * 847.901;
        printf("%9.3lf", d[i]);
    }
    free(d);

    printf("\n");

    char* ch = DYARRAY_CREATE(LEN, char);
    for (int i = 0; i < 10; i++) {
        ch[i] = i + 97;
        printf("%2c", ch[i]);
    }
    free(ch);

    return 0;
}



/*
run:

  0 10 20 30 40 50 60 70 80 90
  0.00  3.14  6.28  9.42 12.56 15.70 18.84 21.98 25.12 28.26
    0.000  847.901 1695.802 2543.703 3391.604 4239.505 5087.406 5935.307 6783.208 7631.109
 a b c d e f g h i j

*/

 



answered Jun 2, 2024 by avibootz
edited Jun 3, 2024 by avibootz
...