简体   繁体   中英

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 *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). You need to use strlen instead.

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). The use of strcpy here also takes care of null termination.

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() 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] . 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.

For sizeof(newCommand) you probably need size , and for sizeof(array[i]) , you probably need strlen(array[i]) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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