试图弄清楚为什么我的char数组在一个类或结构中不接受所有字符,就像通常不在类或结构中那样。
#include <iostream>
using namespace std;
const int SIZE = 10;
struct A{
char address[SIZE];
}
int main(){
char address_from_main[SIZE];
A a;
address_from_main[2] = 9;
cout<<"address from main: "<<address_from_main[2]<<endl;
a.address[2] = 9;
a.address[3] = 'a';
cout<<"show 2: "<<a.address[2]<<" , but didnt show"<<endl;
cout<<"show 3: "<<a.address[3]<<" , this one did"<<endl;
输出=来自main的地址:9 \ n显示2:,但没有显示\ nshow3:,这个确实
这怎么可能? 有没有人知道如何解决这个问题?
非常感谢。
答案 0 :(得分:0)
在你的第一个例子中,正如你所说的那样,工作正常,但这是不可能的,因为你声明的数组是char array
,并且你将numeric
值存储为int value
在它。
address[2] = 9;//assigning a int value not a character
cout<<address[2]<<endl;// hence will not print 9 but some junk value
address[2] = '9';//Correct, assigning a numeric character
cout<<address[2]<<endl;// Will print 9
另请阅读有关整数和字符的内存分配,并了解两者的字节分配有什么区别。
答案 1 :(得分:0)
猜猜有一个无符号的字谜就行了。最终
#include <iostream>
#include <fstream>
using namespace std;
struct Frame {
unsigned char total_frame[16];
int length_frame = 5;
int checksum;
bool checksum_good = 1;
bool complete = 1;
};
int main(){
Frame total;
// open a file in read mode.
ifstream infile;
infile.open("input-file.txt");
cout << "Reading from the file" << endl;
//reading from the file
for(int i=0; i<16; ++i){
cin>>total.total_frame[i];
}
cout<<"read"<<endl;
//reading out from the buffer to the screen
for(int i=0; i<16; ++i){
cout<<total.total_frame[i]<<endl;
}
return 0;
}