我的 strncat 版本将一个太多的字符复制到目的地,我不知道为什么。
#include <stdio.h>
#define MAX_CHARS 20
void nconcatenate(char *start, char *end, int n)
{
if(sizeof start + n > MAX_CHARS)
return;
while(*start++);
start--; /* now points to the final char of start, the \0 */
int i;
for(i = 0; (*start++ = *end++) && i < n; i++);
*start = '\0';
}
int main()
{
char start[MAX_CHARS] = "str";
char *end = "ingy!";
nconcatenate(start, end, 3);
printf("start = %s\n", start);
return 0;
}
使用 3 作为 'n' 输出
stringy
这是一个太多的字符。