是否可以在数据变量中存储多种数据类型,例如char *?
举个例子,它打印val1(一个整数),val3打印到val5(字符),但是第二个整数打印0,浮点打印0.00。
有关如何执行此操作的任何线索?
任何帮助表示感谢。
#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;
}
答案 0 :(得分:1)
嗯马洛克怪癖。当我在我的机器上尝试这个时,我会得到与你相同的东西。但奇怪的是,当我将指针移动到指针增量之外时,我得到secondInteger(56)的正确值,但仍然为浮动值的0.00。不确定是什么解释了这种行为,但我敢打赌它与字节对齐有关。我需要考虑更多。
#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);
}
就像aib一样,我会说使用结构,但是因为你使用了malloc,你可能已经知道使用结构了,只是要求它看看为什么它表现出这种行为:)
答案 1 :(得分:0)
是的,但使用struct要容易得多。
您的示例似乎正在编写我的编译器,但是我太懒了,无法证明它符合标准(未定义的行为等)。这是您应该使用struct
:)的另一个原因。 / p>
答案 2 :(得分:0)
由于这是标记的C ++,我建议你学习类。以下是开始将代码放入class
:
#include <iostream>
#include <iomanip>
#include <string>
class data
{
private:
int first_int_;
int second_int_;
std::string chars_;
float float_value_;
public:
data(int first_int, int second_int, const std::string& chars, float float_value)
:first_int_(first_int)
,second_int_(second_int)
,chars_(chars)
,float_value_(float_value)
{
}
void print(std::ostream& os) const
{
os << "val1 = "
<< first_int_
<< ", val2 = "
<< second_int_
<< ", val3-5 = "
<< chars_
<< ", val6 = "
<< std::setprecision(3)
<< float_value_
<< std::endl;
}
};
int main ()
{
data d(4, 56, "tes", 3.14f);
d.print(std::cout);
return 0;
}