Home > Back-end >  C - How to give a name to a struct dynamically
C - How to give a name to a struct dynamically

Time:03-14

I am trying to change the number that identifies different structures dynamically (being the last digit of the struct name meant to be the same as the i variable). Here is an example of what I mean:

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

struct Person {
    char * name;
    char * job;
    int age;
};

int main () {
    time_t t;
    srand((unsigned) time(&t));

    long random = rand() % 20;
    for (int i = 0; i != (random   1); i  ) {
        struct Person strcat("Person", i");
    }
    return 0;
}

I would like that for each i the struct's name changed. So let's say that i = 2. I would like the struct name to be Person2.

Is there any way for me to do this in C?

CodePudding user response:

No, that is not possible. identifiers in C don't change at run-time. In fact, for variables, they generally don't even exist at runtime.

As @VladFromMoscow suggests, what you're probably after is an array of struct Person's, e.g.

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

struct Person {
    char * name;
    char * job;
    int age;
};

#define MAX_PERSON_NAME_LENGTH 50
#define MAX_NUM_PERSONS 20

int main () {
    time_t t;
    srand((unsigned) time(&t));

    long random = rand() % MAX_NUM_PERSONS;
    struct Person persons[random];

    for (int i = 0; i != (random   1); i  ) {
        persons[i].name = malloc(MAX_PERSON_NAME_LENGTH   1);
        if (persons[i].name != NULL) {
            sprintf(persons[i].name, "The %d'th person", i);
        }
        else {
            perror("allocating memory for a person name");
            exit(EXIT_FAILURE);
        }
    }
    // do something with persons
    return 0;
}

CodePudding user response:

no, but there's no need for such a function anyway. you can achieve what you want by simply creating an array of structs. So, you will access them by doing Person[0], Person[1] etc.. instead of creating 1 different name for each structure

  • Related