简体   繁体   English

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

[英]how to manually concat a char **args to char *args

so I'm trying to write a function that concats a char**args to a char*args What I have so far is": 因此,我正在尝试编写一个将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;                          

} }

this doesn't seem to work. 这似乎不起作用。 Anyone know what's wrong? 有人知道怎么了吗?

I'd do it like this (untested): 我会这样做(未试):

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]);
}

First, your size calculation was wrong. 首先,您的尺寸计算错误。 You wanted the size of the strings, but sizeof(array[i]) gives you the size of a single element in your array which is a pointer and thus 4 (32-bit) or 8 (64-bit). 您需要字符串的大小,但是sizeof(array[i])会给您数组中单个元素的大小,它是一个指针,因此为4(32位)或8(64位)。 You need to use strlen instead. 您需要改用strlen

Next, your manual copying was also off. 接下来,您的手动复制也已关闭。 It's easier to do it with a moving pointer and strcpy (which is to be avoided normally but we've calculated the sizes with strlen already so it's OK here). 使用移动指针和strcpy可以更轻松地完成操作(通常应避免这种情况,但我们已经使用strlen计算了大小,因此在这里可以)。 The use of strcpy here also takes care of null termination. 在这里使用strcpy还可以处理null终止。

Main issue is that you keep using sizeof() with a pointer argument, whereas I think you are trying to get the size of the corresponding array. 主要问题是您一直使用带有指针参数的sizeof() ,而我认为您正在尝试获取相应数组的大小。

sizeof() can only give you information that's available at compile time, such as the sizes of raw types like char and int , and the sizes of arrays with a fixed length such as a char[10] . sizeof()只能为您提供编译时可用的信息,例如charint等原始类型的大小,以及具有固定长度的数组的大小(例如char[10] The sizes of the strings pointed to by a char* is only computable at run time, because it depends on the exact values passed to your function. char *指向的字符串的大小只能在运行时计算,因为它取决于传递给函数的确切值。

For sizeof(newCommand) you probably need size , and for sizeof(array[i]) , you probably need strlen(array[i]) . 对于sizeof(newCommand)您可能需要size ;对于sizeof(array[i]) ,您可能需要strlen(array[i])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM