how to know the size of a struct

I have some problems,please help me ,thank you.....
I want to know the size of some structs by their name. But ,
I read the name from a txt and the type of the name is string.When I use the function "sizeof()" ,I have problems.If the string is "int",function sizeof gives the size of the string, not the size of int.
How can I use sizeof to know the size of a struct by their name?
Please help,thank you ....
Last edited on
sizeof() does not accept the name of a variable, only the typename. You cannot do what you are asking with sizeof.

All your structs of one type will be the same size. sizeof(structType) will give you the size of all structs of that type.
Last edited on
but i have hundreds of struct names in a txt, i need to read them into string and then get their size....
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <string.h>


#define type_s_return(str, type) if(!strcmp(str, #type)) return sizeof(type)

enum { undef_type = (size_t)-1 };


size_t type_s(const char *str)
{
	type_s_return(str, bool);
	type_s_return(str, signed char);
	type_s_return(str, unsigned char);
	type_s_return(str, char);
	type_s_return(str, short unsigned int);
	type_s_return(str, int);
	/* ... */

	return undef_type;
}
thank you,but this is not a good way...too many types
thank you,but this is not a good way...too many types


But you were happy to deal with all the variables by name? That makes no sense. There will be at least as many variables as types, if you make an instance of each type.

If you have them in a list, open your text editor and using the text editors built-in functions add

cout << sizeof(
to the front of each line, and

);
to the end of each line.

Then cut and paste the whole thing into your code and you will have a sizeof function for every type in the list ready to be compiled.
Last edited on
thank you very much!.... I got it!
Topic archived. No new replies allowed.