r/C_Programming • u/Yha_Boiii • May 28 '26
Struct used directly and not as a template?
Hi,
is it possible to make a struct solely for memory proximity, don't need to make a template out of it for later usage, direct var utilization, Can it be done?
0
Upvotes
27
u/MagicWolfEye May 28 '26
I am not sure what you want to say
17
u/fsteff May 28 '26
Sure it can be done:
(Sorry for the crappy formatting - I'm on a mobile)
9
u/mjmvideos May 28 '26
First, yes. You can do:
But why do you need to keep disparate values in proximity to each other?
14
u/TheChief275 May 29 '26
Learn to ask questions; templates are a C++ concept, and you mean anonymous structs instead. Yes, they work in C, although they are incompatible with every other type, which should be fine for your use case.
4
u/SmokeMuch7356 May 28 '26
Assuming I understand what you're asking...
A
structdefinition such as:is just a type specification, like
intordoubleorchar *; it does not set aside any storage for any data. You have to create an instance of the type in order to actually store anthing:Yes, you can use a
structtype to group otherwise unrelated items in a specific order in close proximity; members of eachstructinstance will be laid out in the order declared with increasing addresses. They will be contiguous, although there may be some unused bytes between members to satisfy any alignment requirements, and those bytes are not directly accessible.What kind of problem are you trying to solve? There may be a better solution.
1
u/Chippors May 30 '26
Anonymous structs is absolutely a thing, as is using structs solely for memory layout.
3
u/SCube18 May 28 '26
My question now is that: aren't stack variables next to each other anyway? Referencing one of the OP's comments
2
u/burlingk May 28 '26
Yes.
You can create a struct anywhere, even directly inside a function.
Where to define it and create it depends entirely on how you want to use it.
It is a good idea to make sure it is properly formed with a variable name and everything though.
1
u/Itap88 May 28 '26
Not sure what you're trying to say. I think you want to create a struct that is not a valid type after some point in the program, but I'm not sure which point.
1
u/sohang-3112 May 30 '26
What you mean is an anonymous struct in C, yes it's possible: https://www.geeksforgeeks.org/c/g-fact-38-anonymous-union-and-structure/