简体   繁体   English

数组的第一个字符填充了错误的数据C ++

[英]Array's first character gets populated with incorrect data C++

In a header file, I declare a struct with an array and array length like so: 在头文件中,我声明一个结构和数组长度的结构,如下所示:

typedef struct {
    unsigned char *frame;
    int length;
} ResponseFrame ;

extern ResponseFrame rf;

In my main file, I have the following: 在我的主文件中,我有以下内容:

ResponseFrame rf;

int main(void)
{
   while(1) {
      if (receive() == 0x01) {
         uint8_t val;
         rf.length = 6;
         for(int i = 0; i < 6; i++){
            val = receive();
            rf.frame[i] = val;
            transmit(val);            // LINE 1
         }


         for (uint8_t i=0; i<rf.length; i++){
            transmit(rf.frame[i]);    // LINE 2
         }
      }
   }
}

The array I'm receiving is 我收到的阵列是

{ 00 00 FF 00 FF 00 }

The initial transmit responds with this received data [see LINE 1] . 初始发送响应该接收的数据[见LINE 1]。 However, when I try to transmit using the global variable rf.frame [see LINE 2], the first value is different like this ---- 但是,当我尝试使用全局变量rf.frame进行传输时[参见LINE 2],第一个值就像这样----

{ 13 00 FF 00 FF 00 }

Why is that first initial value different like this?? 为什么第一个初始值不同于此?

You never allocate any memory for ResponseFrame.frame , so you're running into undefined behaviour. 您永远不会为ResponseFrame.frame分配任何内存,因此您将遇到未定义的行为。

You're assuming that by doing rf.length = 6; 你假设通过做rf.length = 6; , the size of unsigned char *frame; unsigned char *frame;的大小unsigned char *frame; somehow magically increases, but it doesn't. 不知何故神奇地增加了,但事实并非如此。

If you're certain of the size, you need: 如果您确定尺寸,则需要:

rf.length = 6;
rf.frame = malloc(sizeof(unsigned char) * 6);   //for C

or use a std::vector in C++. 或者在C ++中使用std::vector

Part of the problem might be that it appears to be relying on undefined behavior. 部分问题可能是它似乎依赖于未定义的行为。 It appears (from the shown code) that frame is never initialized. (从显示的代码中)看起来frame永远不会被初始化。 If it is a fixed size, it could be declared as: 如果它是固定大小,则可以声明为:

unsigned char frame[6];

Otherwise, it may need a call to malloc to allocate memory for it. 否则,可能需要调用malloc为其分配内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM