I'm a beginner in C programming, and here is a struct definition
struct items
{
char *colour;
char *type;
};
I want to declare the struct, with struct name being the value of its colour
and type
. colour
and type
are both known variables.
So for eg, if colour = red
and type = hat
, the program would declare struct items red_hat = {red, hat};
I have tried the following:
char item_name[32];
snprintf(item_name, sizeof(item_name), "%s_%s", colour, type);
struct items item_name = {colour, type};
But this approach generates a compiler error: conflicting types for ‘item_name’. I realised the compiler is using item_name
as the struct name instead of the string stored in item_name
.
What should I fix?
CodePudding user response:
What you're trying to achieve is called Metaprogramming, which involves code that modifies itself. The C programming language focuses on modifying and processing data rather than source code, values of variables that is. Having the names of variables be automatically generated wouldn't be of any benefit to you as they cannot be used as part of the compiled program (they are only labels for YOU, the programmer to keep track of data) and it is a fundamentally wrong approach to try to do so. In the code you provided the char array item_name
gets assigned with the value "red_hat"
after the call to snprintf()
, but it is not substituted as the variable name of the struct you declared next. The name of your struct is therefore just item_name
, same as the char array you declared earlier. C does not allow variables to be reassigned, hence the compiler generating a conflicting types
error.
You seem to confuse source code with the binary program that is generated by the compiler. The latter operates only on values (data such as chars, ints and pointers expressed in binary) that you assigned to the named variables.
Feel free to ask away, seemingly stupid questions even as my goal is to clarify these concepts to you. You would also benefit greatly from revising core programming concepts, among them the ones I mentioned.