[英]how to manually concat a char **args to char *args
因此,我正在嘗試編寫一個將char ** args合並為char * args的函數。
char *concat(char **array)
{
int size = 0;
int i=0;
int j=0;
int z=0;
while (array[i]!=NULL)
{
printf(" %s \n", array[i]);
size = size + sizeof(array[i])-sizeof(char); //get the total size, minus the
//size of the null pointer
printf("%d \n",size);
i++;
}
size = size+1; //add 1 to include 1 null termination at the end
char *newCommand = (char*) malloc(size);
i=0;
while(i<sizeof(newCommand))
{
j=0;
z=0;
while (array[j][z]!='\0')
{
newCommand[i] = array[j][z];
i++;
z++;
}
j++;
}
newCommand[sizeof(newCommand)-1]='\0';
return newCommand;
}
這似乎不起作用。 有人知道怎么了嗎?
我會這樣做(未試):
int size = 0;
int count = 0;
while (array[count]) {
size += strlen(array[i]);
count++;
}
char *newCommand = malloc(size + 1);
char *p = newCommand;
newCommand[0] = 0; // Null-terminate for the case where count == 0
for (int i = 0; i < count; i++) {
strcpy(p, array[i]);
p += strlen(array[i]);
}
首先,您的尺寸計算錯誤。 您需要字符串的大小,但是sizeof(array[i])
會給您數組中單個元素的大小,它是一個指針,因此為4(32位)或8(64位)。 您需要改用strlen
。
接下來,您的手動復制也已關閉。 使用移動指針和strcpy
可以更輕松地完成操作(通常應避免這種情況,但我們已經使用strlen
計算了大小,因此在這里可以)。 在這里使用strcpy
還可以處理null終止。
主要問題是您一直使用帶有指針參數的sizeof()
,而我認為您正在嘗試獲取相應數組的大小。
sizeof()
只能為您提供編譯時可用的信息,例如char
和int
等原始類型的大小,以及具有固定長度的數組的大小(例如char[10]
。 char *指向的字符串的大小只能在運行時計算,因為它取決於傳遞給函數的確切值。
對於sizeof(newCommand)
您可能需要size
;對於sizeof(array[i])
,您可能需要strlen(array[i])
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.