Вопрос

I have a function that will be passed a void pointer. This pointer can either be an int, char, or float. I know what data type will be passed to me by means of an associated value. For example, below is what my function looks like:

void * (int type, void * data);

If the void pointer I am passed was originally a char type, and I cast it back to a char type, is there a way of determining how many bytes are associated with that pointer? For example, if my function is called as follows:

f(1, (void *)"Hello world");

and I cast the void pointer back to a char pointer

char * p = (char *)data;

Is there some way I can figure out how many bytes were used? Would I possibly have to search for the null character and count how many bytes away it is from the original pointer? What would I have to do to find the size of the int and float as well?

Это было полезно?

Решение

Would I possibly have to search for the null character and count how many bytes away it is from the original pointer?

Yes, if your void* is actually a char* this will work.

What would I have to do to find the size of the int and float as well?

int and float as always the same size (it depends from your architecture, generally 32 or 64 bit. Use sizeof operator to determine the exact size). If you are passing an array of int as void* you haven't any way to find its length.

Generally in these cases it's convinent to pass the size to your function too.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top