我想連接通過argv []傳遞給c字符串的多個參數。我沒有使用char數組,因爲我不想限制通過argv []傳遞的字符數量。Realloc()行爲
這是我如何執行我的程序的一個例子。
可執行-cmd rotn 13的Hello World
char *externalCommand = NULL;
if (argc >= 3 && strcmp(argv[1], "-cmd") == 0)
{
externalCommand = (char *)malloc(sizeof(char) * (strlen(argv[2]) + 1));
strcpy(externalCommand, argv[2]);
for (int i = 3; i < argc; ++i)
{
int textLength = strlen(externalCommand);
externalCommand = (char *)realloc(externalCommand, sizeof(char) * (textLength + 1));
strcpy(externalCommand + textLength, " ");
strcpy(externalCommand + textLength + 1, argv[i]);
}
}
我的目標是與字符串結束的 「externalCommand」 等於 「rotn 13 Hello World」 的 當我經過for循環第一次,externalCommand是「rotn 13」,這是正常的。
當我再次通過循環時,運行realloc()時出現奇怪的行爲。 externalCommand變成了「rotiÍÍÍýýýý«««««««îþîþ」。我知道這些是垃圾值,但我不明白爲什麼realloc()會覆蓋字符串中的數字「13」。
爲了解決這個問題,我可以代替:
externalCommand = (char *)realloc(externalCommand, sizeof(char) * (textLength + 1));
有:
externalCommand = (char *)realloc(externalCommand, sizeof(char) * (textLength + 3));
不覆蓋值13
我想明白爲什麼我需要在重新分配時向textLength添加3。
謝謝,我會用你的第二種方法,因爲它更乾淨:) – Cubia 2014-10-11 20:44:56