سؤال

If I am given a void pointer to an array of elements, is there a way in 'C' to find out what type of elements (i.e. data-type of elements) are stored in the array?

What could possibly happen if I typecast this void pointer to a random data-type and try to traverse the array?

هل كانت مفيدة؟

المحلول

Short answer: No, undefined behaviour.

Long answer: You have to cast the pointer into something that's appropriate. There are ways to figure it out, but only if you pass, along with the void pointer itself, information about the width of each element in the array.

نصائح أخرى

You get in the best options a GPF, in the worst case you'll execute some random code, before a GPF. In C a cast does nothing but "considering" a pointer being of a certain type, the only responsible that cast is valid is you.

You cannot possibly know the types in the array as it is "just a number" containing an address. Casting pointers into a different type is undefined behavior and may yield alignment problems, which may generate a CPU exception depending on your architecture.

There is no general way of doing so, but if you know something about what types of data might be in the variable, and those different data types are distinctive in some way, you can examine the starting bytes of the pointer to try and make an educated guess (you may first want to examine the pointer to determine whether it has any alignment restrictions that would forbid certain data types). Outside of debugging (i.e. you know that something clobbered your pointer, but you're not sure what) there's no good reason to do this.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top