0
#include <stdio.h>

typedef struct {
        int stat1, stat2, stat3;
} X_type;

void createPlayer(char *X) {
        X_type X;
}

int main() {
        createPlayer("Foo");
        createPlayer("Bar");

        return 0;
}

I would like to create a structure ojject based on a string passed to a function. So the above code would create 2 X_type structures called Foo and another called Bar. Is there a way to do this?

Edited by stupendousomega

3
Contributors
2
Replies
18
Views
4 Years
Discussion Span
Last Post by Ancient Dragon
1

Not such that you could use them by that name, no. In C, all variables must be declared at compile time. You can allocate memory at runtime, using malloc(), but you would still need a declared pointer to refer to such memory.

Could you give more detalis as to why you want to do this? I suspect that what you really want is going to be something along the lines of a dynamically allocated structure such as a linked list.

0

maybe add another char* to the struct. Then you would create an array or linked list of these structures so that you can search them to find the one named Foo or Bar. Very time consuming and inconvenient.

typedef struct {
        int stat1, stat2, stat3;
        char name[20];
} X_type;
void createPlayer(char *name) {
        X_type X;
        strcpy(X.name,name);
}

Edited by Ancient Dragon

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.