what is the return type of typeof?
I want to provide the type of an element as parameter to an initialization of an array of pointers to element of an unknown types
something like
void* init(type t)
void* array = malloc(sizeof_type(t)*10));
return array;
}
and later call for example
init(typeof(int))
But I was not able to figure what is the return type of typeof.
I guess the sizeof_type think can be achieved using
malloc((type) 0);
Thanks in adv开发者_如何转开发ance
PS: this if for a vector implementatin if someone can point me to some flexiblecode i would be very thankful as well
I don't usually use gnu (I think it is only in gnu C), but I don't think it's an expression in the normal sense that you can assign its value to a variable and later use it. I think it can only be used in very specific contexts as a type.
From the docs:
The syntax of using of this keyword looks like sizeof, but the construct acts semantically like a type name defined with typedef.
A typeof-construct can be used anywhere a typedef name could be used. For example, you can use it in a declaration, in a cast, or inside of sizeof or typeof.
Why can't you just use sizeof? something like:
int c;
void *p = calloc( 10,sizeof(c) );
What you want is not possible.
typeof() does not really return a type, since it is a keyword which is evaluated at compile-time. It is replaced by the name for the type of its parameter.
Maybe you can You can not use the stringification operator of the preprocessor to make it a string, like this ##typeof(a), but then it would still be impossible to malloc/cast something when you have the type in a string.
This:
#define INIT(t) (malloc(sizeof(t) * 10))
may be used like this:
int* a = INIT(int);
or possibly like this:
void* b = INIT(typeof(c));
or even this:
void* b = INIT(c);
since sizeof(c) == sizeof(typeof(c))
.
I know your question wasn't tagged as such, but if you happen to be able to use C++, you may want to look into using template classes. Libraries like STL use templates to provide (type) universal containers and algorithms.
http://www.cplusplus.com/doc/tutorial/templates/
http://en.wikipedia.org/wiki/Template_%28programming%29
You can use a macro for this purpose:
#define INIT(t) ((t*) init_1(sizeof(t)))
void *init_1(size_t sz) {
void *array = malloc(sz * 10);
return array;
}
Then you use like:
int *array = INIT(int);
精彩评论