检查 char 数组是否不是垃圾? (有效字符)

Check if char array is not garbage? (valid chars)

我有一个 char 数组,它在硬件中从一些 EEPROM 设备读取数据,如果里面没有数据,它的值可以是任何东西(垃圾)。

我想检查他的值是否是垃圾并且有一些有效字符

                       for(int k=address;k<address+MEM_MAX_LEN;k++)
                       {
                           charBuf[k-address]= EEPROM.read(k);
                           if(charBuf[k-address]=='*')
                         {
                              charBuf[k-address]='[=10=]';
                              break;
                         }

使用 strlen>1 时,我没有得到想要的响应(很明显)。

如何查看?

在使用之前将它设置为非随机的东西并测试它是否已经改变?

您永远无法确定,因为垃圾可能看起来像有效文本,但您可以做出合理的猜测。像这样,假设一个有效的字符串应该以 NUL 结尾并且只包含可打印的字符:

#include <ctype.h> // For isprint

// ....

int length = 0;
while (length < MEM_MAX_LEN && charBuf[length] != '[=10=]')
    ++length;

if (length == 0) {
    printf("Empty string. Probably garbage!\n");
    return 0;
}

if (length == MEM_MAX_LEN) {
    printf("No NUL byte found. Probably garbage!\n");
    return 0;
}

for (int i = 0; i < length; ++i) {
    if (!isprint((unsigned char)charBuf[i])) {
        printf("Unprintable char (code %d) at position %d. Probably garbage!\n",
               (unsigned char)charBuf[i], i);
        return 0;
    }
}

printf("String consists of %d printable characters. Probably not garbage!\n", length);
return 1;

考虑到 "garbage values" 可能包含任何值,包括值 0,也就是空终止符,并且考虑到评论中发布的 "valid" 的定义:

the definition of valid is all abc-xyz , and all numbers 0-9. (for example abc456efg89)

然后简单地写一个这样的函数:

#include <ctype.h>
#include <stdbool.h>
#include <stdint.h>

bool is_valid (const uint8_t* data, size_t size)
{
  for(size_t i=0; i<size; i++)
  {
    if( !isalnum(data[i]) )
      return false;
  }

  return true;
}

请记住,对于空格和空终止符,这将 return 错误。您将无法假设一个字符串正确地以 null 终止,也不能假设值 0 总是表示字符串的结尾。