[英]Copy char* to another char[]
我有一個關於字符串/字符的簡單問題。 我已經嘗試實現這樣的基本系統;
#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),這很簡單。
您仍然需要在末尾放置一個以null終止的char( \\0
)。
char n[5] = { '\0' }; // Initializes the array to all \0
strncpy(n, input, 4);
您的n
字符必須為5個字節大(4個字符+空終止符)。 之后您會看到gonk,因為沒有空終止符\\0
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.