如何手动将char ** args连接到char * args

时间:2011-10-13 08:18:38

标签: c

所以我正在尝试编写一个将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;                          

}

这似乎不起作用。谁知道什么是错的?

2 个答案:

答案 0 :(得分:3)

我会这样做(未经测试):

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也会处理空终止。

答案 1 :(得分:0)

主要问题是你继续使用带有指针参数的sizeof(),而我认为你正试图获得相应数组的大小。

sizeof()只能为您提供编译时可用的信息,例如charint等原始类型的大小,以及具有固定长度的数组的大小,例如一个char[10]。 char *指向的字符串大小只能在运行时计算,因为它取决于传递给函数的确切值。

对于sizeof(newCommand),您可能需要size,对于sizeof(array[i]),您可能需要strlen(array[i])

相关问题