c ++在类外部分配char数组的索引

问题描述 投票:-2回答:2

试图弄清楚为什么我的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 \ nshow 2 :,但是没有显示\ show:,这个确实如此

这怎么可能?有人知道如何解决这个问题吗?

非常感谢。

c++ arrays class struct char
2个回答
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

另请阅读有关整数和字符的内存分配,并了解两者的字节分配有何区别。


0
投票

猜猜有一个未签名的char就可以了。最终。

#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;
}
© www.soinside.com 2019 - 2024. All rights reserved.