您需要将缓冲区大小与指针一起传递。
int
ascii_to_morse(lookuptable *table,
char* morse, int morse_size,
char* ascii);
缓冲区大小不一定与字符串的当前长度相同(可以使用 strlen 找到)。
上面给出的函数将读取 ascii 字符串(不需要知道缓冲区大小,因此不会传递)并写入 morse 指向的缓冲区,大小为 morse_size。它返回写入的字节数(不包括 null)。
编辑:这里是这个函数的一个实现,虽然它无法为摩尔斯电码使用正确的值,但它显示了如何管理缓冲区:
typedef void lookuptable; // we ignore this parameter below anyway
// but using void lets us compile the code
int
ascii_to_morse(lookuptable *table,
char* morse, int morse_size,
char* ascii)
{
if (!ascii || !morse || morse_size < 1) { // check preconditions
return 0; // and handle it as appropriate
// you may wish to do something else if morse is null
// such as calculate the needed size
}
int remaining_size = morse_size;
while (*ascii) { // false when *ascii == '\0'
char* mc_for_letter = ".-"; //BUG: wrong morse code value
++ascii;
int len = strlen(mc_for_letter);
if (remaining_size <= len) { // not enough room
// 'or equal' because we must write a '\0' still
break;
}
strcpy(morse, mc_for_letter);
morse += len; // keep morse always pointing at the next location to write
remaining_size -= len;
}
*morse = '\0';
return morse_size - remaining_size;
}
// test the above function:
int main() {
char buf[10];
printf("%d \"%s\"\n", ascii_to_morse(0, buf, sizeof buf, "aaa"), buf);
printf("%d \"%s\"\n", ascii_to_morse(0, buf, sizeof buf, "a"), buf);
printf("%d \"%s\"\n", ascii_to_morse(0, buf, sizeof buf, "aaaaa"), buf);
return 0;
}