arrays - 为什么将字符“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”。
注意:我在测试套件之外运行了相同的代码,结果很好,即它通过了测试。
解决方案
推荐阅读
- mongodb - 错误信息查找管道必须是字符串,是数组类型
- llvm - 一个llvm程序生成多少个ast?
- android - 未知主机(我的代理 ip)。您可能需要在 android studio 中调整 Gradle 中的代理设置
- java - 创建一个后端 java RESTful API,它将与存储在云上的数据库进行通信
- vb.net - 在 vb.net 中裁剪图像
- angular - Ngrx 效果:输出未添加到操作流中
- go - 如何获得没有时区的时间?
- python - == 0在python中的意义。(初学者)
- html - 在 Wordpress 中将图像与文本对齐的最佳方法是什么?
- angular - 导航后Angular 6重定向回主页