为什么我的空字符数组以 6 开头?

Why does my empty character array start with a length of 6?

当我打印出临时字符串的长度时,它从一个随机数开始。这个 for 循环的目标是过滤掉所有不是字母的东西,它在大多数情况下都有效,但是当我打印出过滤后的字符串时,它 returns 过滤后的字符串,但前后有一些额外的随机字符字符串。

#define yes 1000
...
char stringed[yes] = "teststring";
int len = strlen(text);

char filt[yes];

  for (int i = 0; i < len; i++) {
    if (isalpha(stringed[i])) {
      filt[strlen(filt)] = tolower(stringed[i]);
    }
  }

线路至少有两个问题:

temp[strlen(temp)] = "[=10=]";
  1. 编译器应该急于将指针转换为整数。您需要 '[=12=]' 而不是 "[=13=]"。 (这可能是一些奇怪字符的原因;地址的最低有效字节可能存储在空字节上,使其和其他随机字符可见,直到字符串打印在某处遇到另一个空字节。)

  2. 在修复该问题后,代码会在标记字符串结尾的空字节上小心地写入一个空字节。

此时您可能不应该使用 strlen()(或在循环中使用它的许多其他点)。

您应该在循环中多使用 i。如果您的目标是消除非字母字符,您可能需要两个索引,一个用于 'next character to check',一个用于 'next position to overwrite'。循环后,需要用空字节覆盖'next position to overwrite'。

int j = 0;   // Next position to overwrite
for (int i = 0; i < length; i++)
{
    if (isalpha(text[i]))
        temp[j++] = text[i];
}
temp[j] = '[=11=]';

对于初学者来说,字符数组

char temp[MAX];

未初始化。它具有不确定的值。

所以这些陈述

printf("NUM:[%i] CHAR:[%c] TEMP:[%c] TEMPSTRLEN:[%i]\n", i, text[i], temp[strlen(temp)], strlen(temp));

  temp[strlen(temp)] = tolower(text[i]);

具有未定义的行为,因为您可能无法将标准函数 strlen 应用于未初始化的字符数组。

此声明

  temp[strlen(temp)] = "[=12=]";

同样无效。

在赋值语句的左侧,使用了字符串文字 "[=17=]",它被隐式转换为指向其第一个字符的指针。

所以这些陈述

  length = strlen(temp);

  printf("[%s]\n", temp);

没有意义。

看来你的意思是下面的

#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define MAX 1000

int main(void) 
{
    char text[MAX] = "teststring";
    size_t length = strlen(text);

    char temp[MAX] = { '[=14=]' };
    // or
    //char temp[MAX] = "";


    for ( size_t i = 0; i < length; i++) 
    {
        if (isalpha( ( unsigned char )text[i] ) ) 
        {
            printf("NUM:[%zu] CHAR:[%c] TEMP:[%c] TEMPSTRLEN:[%zu]\n", i, text[i], temp[strlen(temp)], strlen(temp));      

            temp[strlen(temp)] = tolower(text[i]);
            temp[i+1] = '[=14=]';
        }
    }

  length = strlen(temp);

  printf( "[%s]\n", temp );

  return 0;
}

程序输出为

NUM:[0] CHAR:[t] TEMP:[] TEMPSTRLEN:[0]
NUM:[1] CHAR:[e] TEMP:[] TEMPSTRLEN:[1]
NUM:[2] CHAR:[s] TEMP:[] TEMPSTRLEN:[2]
NUM:[3] CHAR:[t] TEMP:[] TEMPSTRLEN:[3]
NUM:[4] CHAR:[s] TEMP:[] TEMPSTRLEN:[4]
NUM:[5] CHAR:[t] TEMP:[] TEMPSTRLEN:[5]
NUM:[6] CHAR:[r] TEMP:[] TEMPSTRLEN:[6]
NUM:[7] CHAR:[i] TEMP:[] TEMPSTRLEN:[7]
NUM:[8] CHAR:[n] TEMP:[] TEMPSTRLEN:[8]
NUM:[9] CHAR:[g] TEMP:[] TEMPSTRLEN:[9]
[teststring]

编辑:下次不要如此大意地改变你的问题,因为这会使问题的读者感到困惑。