我使用strstr来搜索括号的开头和结尾,这样我就可以从我实际想要/需要的信息中过滤掉在UART上发送的不正确条目.

我有我的中断存储字符到一个数组和递增计数器. 下面是我的main函数中的代码:

  volatile char     UART_RX_Buffer[128]; // updated in UART
  volatile uint16_t UART_Byte_Counter = 0; // updated in UART
  
  while (1)
  {
        if(strstr(&UART_RX_Buffer[0], "{") != NULL)
        {
            if(strstr(&UART_RX_Buffer[0], "}") != NULL)
            {
                char *ret;
                int startindex;

                ret = strstr(&UART_RX_Buffer[0], "{");
                startindex = (ret - UART_RX_Buffer);

                // Clear out UART array and counter
                char Empty_Buffer[128] = {0};
                memcpy (UART_RX_Buffer, Empty_Buffer, sizeof(UART_RX_Buffer));
                UART_Byte_Counter = 0;
            }
        }
  }

因此,如果我发送它,比如说012{345,678},它会将startindex设置为3(这就是我想要的).它成功地进入循环,设置了startindex,并正确地清除了UART_RX_BUFFER和计数器.

奇怪的是,它只在第一次通过时才起作用.如果我第二次发送它,我可以看到缓冲区保存的数据与第一次相同...但它没有进入第一个循环,识别"{"字符.如果我没有正确地处理UART中断,并且缓冲区没有被正确填充,我会看到一个问题...但情况似乎并非如此.我真的不明白为什么我会得到与看起来相同的数据不同的结果(特别是如果我在try 运行该行时可以确认数据在UART缓冲区中).

Clearly I'm missing something. Any ideas what might be causing this? If it helps, it's an STM32L4R5ZI chip (though I would assume this is a C issue and not device specific). I'll include screenshots from the debugger all the same in case it helps. Thanks in advanceenter image description here!

推荐答案

C中的strstr问题

不,这始终是您的代码问题.strstr,编译器、链接器和硅片都正常.

(尤其是如果我在以下情况下确认数据在UART缓冲区中 试图经营这条线).

但这并不是你认为你拥有的数据:)

enter image description here The C sting is empty as it starts with the null terminating character. strstr sees the empty string. Your buffer-filling algorithm is definitely broken.

I can even tell you that you have not updated the index or pointer of the current buffer position as '0' goes to the place where the previous transition ended: enter image description here

C++相关问答推荐

C限制限定符是否可以通过指针传递?

Pure Win32 C(++)-除了替换控件的窗口程序之外,还有其他方法可以在输入时禁用按钮吗?

如何在不修改字符串缓冲区早期使用的情况下覆盖字符串缓冲区

单指针和空参数列表之间的函数指针兼容性

在C语言中使用scanf()时我无法理解的警告

MISRA C:2012 11.3违规强制转换(FLOAT*)到(uint32_t*)

使用C时,Windows CMD中的argc参数是否包含重定向命令?

致命:ThreadSaniizer:在Linux内核6.6+上运行时意外的内存映射

Clang警告称,`ffi_type`与`sizeof`不兼容

将变量或参数打包到 struct /联合中是否会带来意想不到的性能损失?

CS50判断灯泡运动的问题,判断时多出一个灯泡,但不在终端上

通过k&;r语法的c声明无效

递归打印二维数组(C编程)

如何组合两个宏来初始化C语言中的字符串数组?

为什么一个在线编译器拒绝这个VLA代码,而本地的Apple clang却不拒绝;t?

使用 strtok 多次分割一个字符串会导致意外行为

无法将字符串文字分配给 C 中的字符数组

使用邻接表创建图

无法在线程内用 C 打印?

当 a 是代码块时使用逗号运算符 (a, b)