-1

我有一个关于字符串/字符的简单问题。我试图实现这样的基本系统;

#include <stdio.h>
#include <string.h>

int main()
{
    //I'll use 'char*' for socket receive buffer!
    const char* input = "This is a test!";
    char n[4];
    strncpy(n, input, 4);
    printf("%s\n%i\n", n, strlen(n));
    return 0;
}

我得到了这个输出:

Thisd0@
7

怎么了?这是一个简单的 for/while 循环 (IDK)。

4

2 回答 2

7

您仍然需要在末尾放置一个以空值结尾的字符 ( \0)。

char n[5] = { '\0' }; // Initializes the array to all \0
strncpy(n, input, 4);
于 2013-09-23T16:03:22.113 回答
1

您的nchar 需要 5 个字节大(4 个字符 + 空终止符)。之后你会看到 gonk 因为没有 null-terminator \0

于 2013-09-23T16:04:06.590 回答