首页 > 解决方案 > 为什么将字符“T”附加到此代码?

问题描述

我的代码

文件:首字母缩略词.c

#include <ctype.h>
#include <stdlib.h>

#include "acronym.h"

char *abbreviate(const char *phrase) {
  // strcmp results to 0 when strings are equal, so put '!'
  if (!phrase || !strcmp(phrase, "")) return NULL;

  static char *abbreviated;
  char buffer;
  unsigned int j = 0;
  abbreviated = malloc(0);
  for (size_t i = 0; phrase[i]; i++) {
    // if buffer not empty and char is a letter then append abbreviated
    if (!buffer && (isalpha((unsigned char)phrase[i])) {
      buffer = phrase[i];
      abbreviated = realloc(abbreviated, (j + 1) * sizeof(char));
      abbreviated[j] = toupper(phrase[i]);
      j++;
      continue;
    }
    if (buffer)
      if (!isalpha((unsigned char)phrase[i]) && phrase[i] != '\'')
        buffer = 0;  // set to false to represent empty buffer
  }
  return abbreviated;
}

测试套件:

#include <stdlib.h>
#include <string.h>

#include "../src/acronym.h"
#include "vendor/unity.h"

static void check_abbreviation(char *phrase, char *expected) {
  char *actual = abbreviate(phrase);
  TEST_ASSERT_EQUAL_STRING(expected, actual);
  free(actual);
}

static void test_consecutive_delimiters_abbreviation(void) {
  char *phrase = "Something - I made up from thin air";
  char *expected = "SIMUFTA";
  check_abbreviation(phrase, expected);
}

问题

每个测试都通过但test_consecutive_delimiters_abbreviation失败并出现以下错误:

test/test_acronym.c:13:test_consecutive_delimiters_abbreviation:FAIL:Expected 'SIMUFTA' Was 'SIMUFTAT'

我不知道为什么最后附加了“T”。

注意:我在测试套件之外运行了相同的代码,结果很好,即它通过了测试。

标签: arrayscstringpointers

解决方案


推荐阅读