What is the return type?

I want to specify the type of an element as a parameter to initialize an array of pointers to an element of unknown types

sort of

void* init(type t) void* array = malloc(sizeof_type(t)*10)); return array; } 

and then call for example

  init(typeof(int)) 

But I could not understand what a return type is.

I think sizeof_type can be achieved with

  malloc((type) 0); 

Thanks in advance

PS: this, if for a vector implementation, if someone can point me to some kind of flexible code, I would also be very grateful

+4
source share
6 answers

Why can't you just use sizeof? sort of:

 int c; void *p = calloc( 10,sizeof(c) ); 
+4
source

I usually donโ€™t use gnu (I think itโ€™s only in gnu C), but I donโ€™t think it is an expression in the normal sense that you can assign its value to a variable and then use it. I think it can only be used in very specific contexts as a type.

From the docs:

The syntax for using this keyword looks like sizeof, but the construct acts semantically like a type name defined using typedef.

You can use the type construct anywhere you can use the name typedef. For example, you can use it in declarations, in castings, or inside sizeof or typeof.

+3
source

What you want is impossible.

typeof () does not really return a type, since it is a keyword that evaluates at compile time. It is replaced by the type name of its parameter.

Perhaps you can . You cannot use the preprocessor gating operator to make it a string, for example, it is ## typeof (a), but then it would still be impossible to malloc / cast something when you have a type in the string.

+2
source

It:

 #define INIT(t) (malloc(sizeof(t) * 10)) 

can be used as follows:

 int* a = INIT(int); 

or perhaps like this:

 void* b = INIT(typeof(c)); 

or even this:

 void* b = INIT(c); 

since sizeof(c) == sizeof(typeof(c)) .

+1
source

I know that your question was not flagged as such, but if you manage to use C ++, you may need to study template classes. Libraries such as STLs use templates to provide (type) generic containers and algorithms.

http://www.cplusplus.com/doc/tutorial/templates/

http://en.wikipedia.org/wiki/Template_%28programming%29

0
source

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); 
0
source

Source: https://habr.com/ru/post/1315931/


All Articles