Reputation: 33
So I started a programming project, and I found out it would make everything easier if I could just make a pointer without declaring it as char*
, int*
and so on and just specify the size somewhere else. I searched around but couldn't find anything useful.
Right now my idea would be to make everything a char*
and just unite them with bit shifting and or operations if it isn't a string. If this is too low level for C, what language lets me do this, I prefer not to use assembly because it isn't cross platform enough.
edit: So i forget to mention it should allocate memory at runtime, and to not waste too much memory i want to allocate memory depending on the size. For example i want to allocate 1 byte for char sized values and 2 bytes for int sized values and so on. The size is predefined in a file, but is not known until the file is read which should be read in runtime rather then compiling time.
Upvotes: 0
Views: 2107
Reputation: 1041
I think there is some misconception about data types, and what compile-time data types and run-time data types are. So first an example from C#, which is a programming language, where the distinction between compile-time data types and run-time data types matters. In C# you can write something like
IEnumerable<int> myEnumerable = new List<int>();
Here, the myEnumerable
object has compile-time data type IEnumerable<int>
and run-time data-type List<int>
.
However, in the C programming language, there is no related concept, because C doesn't have such a strong type system. Essentially, in the C programming language, all information you store in variables is binary data that is stored somewhere in the virtual memory of the process. This data has no type information assigned to it. As a consequence, you cannot reconstruct the type of the data by simply looking at the data. In the C programming language, you can cast the data to any data type you like.
As already mentioned by other users, you can use void
if you don't know the specific type of your data.
Upvotes: 1
Reputation:
There is a generic pointer type in C for exactly this reason: void *
.
You can convert any data pointer type implicitly to and from void *
:
char foo[] = "bar";
void *ptr = foo;
// ...
char *str = ptr;
But be aware that you still have to know the correct type. Accessing an object through a pointer of the wrong type would be undefined behavior.
There are two things you can't do with void *
:
You can't do pointer arithmetics on it (this includes indexing). void
is an incomplete type, so it doesn't have a known size. Some compilers allow arithmetics on void *
by assuming the size of a char
, but this is an extension and not portable.
You can't dereference a void *
. void
is "nothing", so it wouldn't be meaningful.
Upvotes: 10