Is it possible to store multiple data types in a data variable, for instance char *?
Take this example, it prints val1 (an integer), and val3 to val5 (chars), but prints 0 for the second integer, and 0.00 for the float.
Any clues as how to do this?
Any help appreciated.
#include <iostream>
static void printData(char *what) {
int val1, val2, counter = 0;
char val3, val4, val5;
float val6;
val1 = *((int *)what+counter);
counter += sizeof(int);
val2 = *((int *)what+counter);
counter += sizeof(int);
val3 = *((char *)what+counter);
counter += sizeof(char);
val4 = *((char *)what+counter);
counter += sizeof(char);
val5 = *((char *)what+counter);
counter += sizeof(char);
val6 = *((float *)what+counter);
printf("val1 = %d, val2 = %d, val3-5 = %c%c%c, val6 = %.2f", val1, val2, val3, val4, val5, val6);
}
int main (int argc, const char *argv[]) {
char *data = (char *)malloc((sizeof(int) * 2) + (sizeof(char) * 3) + sizeof(float));
int integer = 4, secondInteger = 56;
char test[3] = { 't', 'e', 's' };
float floatValue = 3.14f;
int counter = 0;
*(data) = integer;
counter += sizeof(int);
*(data + counter) = secondInteger;
counter += sizeof(int);
*(data + counter) = test[0];
counter += 1;
*(data + counter) = test[1];
counter += 1;
*(data + counter) = test[2];
counter += 1;
*(data + counter) = floatValue;
printData(data);
return 0;
}
Hmmm malloc quirks. I get the same thing as you when I try this on my machine. Oddly though, when I move the casting outside the pointer increment, I get the correct value for secondInteger (56) but still 0.00 for floatValue. Not really sure what explains this behavior, but I bet it has something to do with byte alignment. I’ll need to think about it more.
Like aib, I’d say to use structs, but since you’re using malloc, you probably know already to use structs and are just asking this to see why it exhibits this behavior 🙂