开发平台(Platform): (Ex: VC++, GCC, Linux, ...)
VC 2013 - console
额外使用到的函数库(Library Used): (Ex: OpenGL, ...)
没有
问题(Question):
请问一下, 我有一个结构长这样
typedef struct
{
//int int_a;
char char_a;
char char_b;
char char_c;
char char_d;
int int_a;
}TEST_TYPE;
有一个对应的纯文字档, 内容是
1,2,3,-12345,4
利用下面的fscanf格式读取的时候会发生int_a = -16777216 的错误
fscanf( opfile, "%hhu,%hhu,%hhu,%d,%hhu",
&test_data.char_a,
&test_data.char_b,
&test_data.char_c,
&test_data.int_a,
&test_data.char_d
);
但是只要把结构做一些调整, 变成
typedef struct
{
int int_a;
char char_a;
char char_b;
char char_c;
char char_d;
//int int_a;
}TEST_TYPE;
就能够正确的读出五个值
对于struct来说, 上下两种排列都没有4byte alignment的问题
即便有, 也只是会有padding而已, 不致于造成格式读取错误
请问这个现象是哪里有问题呢?
喂入的资料(Input):
1,2,3,-12345,4
预期的正确结果(Expected Output):
char_a = 1, char_b = 2, char_c = 3, char_d = 4
int_a = -12345
错误结果(Wrong Output):
char_a = 1, char_b = 2, char_c = 3, char_d = 4
int_a = -16777216
程式码(Code):(请善用置底文网页, 记得排版)
void TestFunction()
{
typedef struct
{
int int_a;
char char_a;
char char_b;
char char_c;
char char_d;
//int int_a;
}TEST_TYPE;
TEST_TYPE test_data = {0};
FILE* opfile = 0;
unsigned int index_current = 0;
opfile = fopen( "test.txt", "r" );
fscanf( opfile, "%hhu,%hhu,%hhu,%d,%hhu",
&test_data.char_a,
&test_data.char_b,
&test_data.char_c,
&test_data.int_a,
&test_data.char_d
);
fclose(opfile);
}
补充说明(Supplement):
感谢~~
update