【问题标题】:c++ assigning the index of char array outside a classc ++在类外分配char数组的索引
【发布时间】:2018-03-02 12:03:49
【问题描述】:

试图弄清楚为什么我的 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;

output = address from main: 9\nshow 2: ,但没有显示 \nshow3: ,这个有

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

非常感谢。

【问题讨论】:

  • charint 显示不同...9 != '9'
  • Cannot reproduce 第一个例子。它不输出9
  • anything.. 但它是一个比索引大的常数。说 100。
  • 您是否可能在某些时候使用'9' 而不是9 而只是忘记了' '
  • @Jarod42 UB??也许定义了实现。

标签: c++ arrays class struct char


【解决方案1】:

在您的第一个示例中,正如您所说,这工作正常,但这是不可能的,因为您声明的数组是 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

还可以阅读有关整数和字符的内存分配,看看两者的字节分配有什么区别。

【讨论】:

  • 9 分配给char 并不是完全错误的。 chars 可以用作 8 位整数,并且存在与 int 的隐式转换,这使得这合法。
  • 但如果我这样说:char temp = 9;地址[2] = 温度;然后 cout
  • @nwp,没错,我知道。但你假设它是性格。更正我的回答。谢谢。
  • @Khamaseen,你试过了吗?如果您的编译器这样做,那很奇怪。
  • @Khamaseen 这也不会打印9,它会打印一个标签。
【解决方案2】:

猜猜有一个 unsigned 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-27
    • 1970-01-01
    • 2020-06-01
    • 1970-01-01
    • 2011-04-28
    • 1970-01-01
    • 1970-01-01
    • 2021-07-04
    相关资源
    最近更新 更多