Char 数组意外的空字符

标签 c arrays for-loop

char *placeDelimiter(char message[], int maxSize) {
  int msgSize = strlen(message);  //length of message
  int delSize = (msgSize/maxSize);//how many delimiters are needed
  int remSize = msgSize%maxSize;  //remainder characters
  int newSize = msgSize+delSize;  //new size of message
  if (remSize==0) delSize--;      //if there are no remainders remove , from end

  char *temp = (char *)malloc(newSize+1);
  int delPos = 0;
  int spacing = 0;
  for (int x=0;x<msgSize;x++) {
    if (delPos==maxSize) {
        temp[x] = ',';
        delPos=0;spacing++;
    } else {delPos++;}
    temp[x+spacing] = message[x];
    printf("Char: %c DelPos: %d Spacing: %d\n", temp[x], delPos, spacing);
  }
  temp[msgSize] = '\0';
  return temp;
}

上面的函数每隔设定数量的字符放置一个分隔符 (maxSize)

当函数在输入中给出,例如 “这是一条消息” 以及 4 表示 maxSize 时,输出应为 “这是,一个我,ssag,e”。但是,存在一个问题,即在循环期间给出空字符,该字符显然充当字符数组的末尾

我在循环中添加了 printf 以在过程中提供更多信息,这是给出的输出:

Char: T DelPos: 1 Spacing: 0
Char: h DelPos: 2 Spacing: 0
Char: i DelPos: 3 Spacing: 0
Char: s DelPos: 4 Spacing: 0
Char: , DelPos: 0 Spacing: 1
Char:   DelPos: 1 Spacing: 1
Char: i DelPos: 2 Spacing: 1
Char: s DelPos: 3 Spacing: 1
Char:   DelPos: 4 Spacing: 1
Char: , DelPos: 0 Spacing: 2
Char:  DelPos: 1 Spacing: 2
Char:   DelPos: 2 Spacing: 2
Char: m DelPos: 3 Spacing: 2
Char: e DelPos: 4 Spacing: 2
Char: , DelPos: 0 Spacing: 3
Char: s DelPos: 1 Spacing: 3
Char:  DelPos: 2 Spacing: 3
This, is ,

第二个逗号后面的字符为空,我找不到原因。有谁知道为什么吗?

最佳答案

这段代码有两个问题。一个

temp[x] = ',';

应该是:

temp[x + spacing] = ',';

因为如果条件为假,这就是角色所在的位置。

第二,是我在评论中谈到的 NUL:

temp[msgSize] = '\0';

应该是:

temp[msgSize + spacing] = '\0';

IMO,如果使用两个索引变量而不是偏移量,会更容易理解。像这样的东西:

for (x = 0, y = 0; x < msgSize; ++x, ++y)
{
    if (...)
      temp[y++] = ',';
    temp[y] = message[x]; 
}
temp[y] = '\0';

PS:您应该尝试使用调试器,它使某些事情变得更容易......

关于Char 数组意外的空字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33569534/

相关文章:

php - 我可以在类数组上使用 array_filter() 吗?

ruby - 在 Ruby 中,为什么 Array.new(size, object) 创建一个由对同一对象的多个引用组成的数组?

java - 如何在多个数组中搜索输入值并使用一个或多个 for-each 循环返回值和位置

c# - 在循环中获取每第 100 个值

c - for 循环的值意外下降

c++ - 非(~)与否定(!)

c - 对文本文件中的数字进行排序

c - 是 snprintf(NULL,0,...);行为规范?

MATLAB:嵌套 for 循环每次连续迭代都需要更长的时间

c - 如何将结构存储为链表节点,并且该结构具有 char *words[10] 这是一个已解析的字符串?