2016-01-20 74 views
1

我這樣做是爲了添加一些文字:索引字符數組追加一個字符串

char text[100]; 
strcpy(text, "Hello"); 

char input[] = "random"; 
strncpy(text + strlen(text), input, sizeof(text) - strlen(text)); 

我這樣做,它似乎做工精細的ASCII文本。但是我擔心指針算術不安全。如果輸入是UTF-8會怎麼樣?

僅供參考,當我做text + strlen(text)我得到一個指向句子的末尾,然後追加到句末。

text => |h|e|l|l|o|NUL||||||....

text + strlen(text) => |NUL|||||.....

+1

爲什麼不使用'strcat'? – ameyCU

+0

你對utf-8的關注是什麼? –

+0

其實我很困惑。我擔心「text + 1」不等於文本[1]的情況。 –

回答

2

這就是爲什麼strcat的存在:

char text[100]; 
strcpy(text, "Hello"); 

char input[] = "random"; 
strcat(text, input); 

爲了保證內存敏感的級聯防止溢出,請使用以下修改:

char *text; 

    //allocate memory 
    text = (char *) malloc(15); 
    strcpy(text, "Hello"); 


    char input[] = "random"; 

    //reallocate memory 
    text = (char *) realloc(text, strlen(text)+strlen(input) +1); 
    strcat(text, input); 
    free(text); 
+0

如果在''text''緩衝區不夠大。如果我用''strncat''我還需要計算出多少空的空間''text''右剩下的? –

+1

請記添加到您的解決方案,主叫功能則負責釋放使用後'concat'分配的內存。 – CiaPan

+0

是的,'strcat'簡化了任務 - 但它沒有進行大小測試,並且可能會溢出目標數組,與OP的方法相反。 – CiaPan