我正在嘗試實作一個從 c 字串源復制字符然后將其存盤到陣列目標中的函式。我知道這是 strcpy 但是我不允許呼叫任何函式,也不允許使用任何區域變數。我還必須能夠在其末尾添加一個空終止符,以便陣列本身成為交流字串。numChars 是陣列目標被限制的大小。例如,如果 source 是“apples”并且 numChar 是 2,則前 3 個元素將是 'a'、'p' 和 '\0'。以下是我的嘗試,我該怎么做?
void copyWord(char * destination, const char * source, int numChars){
while(*destination != numChars){
*destination = *source;
destination ;
source ;
}
destination[numChars] = '\0';
}
uj5u.com熱心網友回復:
像這樣的東西應該可以解決問題,您可能應該添加一些錯誤檢查以及檢查函式的引數。
void copyWord(char * destination, const char * source, int numChars)
{
while(numChars-- && *source)
{
*destination = *source ;
}
*destination = '\0';
}
uj5u.com熱心網友回復:
您描述的基本上是strncpy,但是您自己的實作:
void copyWord(char *destination, const char *source, int destSize) {
if ((destination == nullptr) || (destSize <= 0)) {
return;
}
while ((destSize > 1) && (*source)) {
*destination = *source;
destination ;
source ;
destSize--;
}
// destSize is at least 1, so this is safe
*destination = '\0';
}
uj5u.com熱心網友回復:
這是我的嘗試解決方案:
void copyWord(char * destination, const char *source, int numChars){
if(!numChars){
*destination = '\0';
return;
}
while(*source != NULL && numChars --){
*destination = *source;
destination ;
source ;
}
*destination = '\0';
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/506478.html
