[英]C Initialize Character Array from Character Pointer
我的問題應該很簡單。
我需要給函數一個預定義長度的char數組,但是我有一個字符指針,其長度可變,但不超過數組的長度。
這里的代碼:
#define SIZE_MAX_PERSON_NAME 50
char person[SIZE_MAX_PERSON_NAME];
char* currentPerson = "John";
現在如何將John放入person數組,同時將數組的其余部分設置為0(/ NUL)?
這樣我就可以
BINARY DATA: "John/NUL/NUL/NUL/NUL/NUL/NUL/NUL/NUL/NUL/NUL/NUL/NUL/NUL/NUL....."
在我的記憶中?
很抱歉,如果這太愚蠢了,但我現在似乎找不到解決方法。
首先,對固定大小的數組進行零初始化:
// Using memset here because I don't know if the whole copy operation can or will be used
// multiple times. We want to be sure that the array is properly zero-initialized if the next
// string to copy is shorter than the previous.
memset(person, '\0', SIZE_MAX_PERSON_NAME);
然后,將可變大小的字符串復制到其中:
strcpy(person, currentPerson);
如果您不確定currentPerson
是否適合person
:
strncpy(person, currentPerson, SIZE_MAX_PERSON_NAME - 1);
請注意,如果出現以下情況, strncpy
還會將數組的剩余字節零初始化。
strlen(currentPerson) < SIZE_MAX_PERSON_NAME - 1
因此,您基本上有兩個選擇:
memset(person, '\0', SIZE_MAX_PERSON_NAME);
strcpy(person, currentPerson);
要么 :
strncpy(person, currentPerson, SIZE_MAX_PERSON_NAME - 1);
person[SIZE_MAX_PERSON_NAME - 1] = '\0';
發布此答案后,問題從C ++重新標記為C。
使用std::string
,如下所示:
// "using namespace std;" or "using std::string;", then:
string const person = currentPerson;
old_c_function( person.c_str() );
要在C級別執行操作(我建議您不要這樣做),請首先使用類型常量替換不必要的#define
:
int const max_person_name_size = 50;
然后零初始化您的數組:
char person[max_person_name_size] = {};
(注意:這里沒有愚蠢的memset
。)(還請注意:這種歸零只是一種預防措施。您想要這樣做。但是因為strcpy
可以確保尾隨零字節,所以它實際上不是必需的。)
然后只需復制字符串:
assert( strlen( current_person ) < max_person_name_size );
strcpy( person, current_person );
但是不要這樣做。 使用std::string
代替。
更新 :花了幾分鍾的時間做其他事情,使我意識到,與到目前為止所有其他答案一樣,這個答案是完全錯誤的 。 OP在其他地方的評論中指出
”我在庫中有一個僅包含字符數組的函數。 不是字符指針。
因此,這顯然是一個誤解。
唯一有意義的方法是通過函數修改數組,然后std::string::c_str()
不是解決方案。 但是,如果將std::string
的長度設置為足以用於C函數的長度,則仍可以使用。 可以這樣:
person.resize( max_person_name_size );
foo( &person[0] ); // Assuming foo modifies the array.
person.resize( strlen( person.c_str() ) );
使用文字,您可以執行以下操作:
char person[SIZE_MAX_PERSON_NAME] = "John";
如果c-string不是文字,則必須使用strcpy
進行復制
strcpy(person, currentPerson);
這是存在strncpy
唯一原因:
將一個字符串(直到0終止符或緩沖區末尾)放入固定長度的數組中,然后將其余部分歸零。
這不能確保0終止,因此可以避免其他任何情況。
7.24.2.4
strncpy
函數#include <string.h> char *strncpy(char * restrict s1, const char * restrict s2, size_t n);
2
strncpy
函數將從s2
指向的數組復制到s1
指向的數組中,最多復制n
字符(不復制跟隨空字符的字符)。 308)如果復制發生在重疊的對象之間,則行為是不確定的。
3如果s2
指向的數組是短於n
字符的字符串,則將空字符附加到s1
指向的數組的副本中,直到總共寫入了n
字符。
4strncpy
函數返回s1
的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.