Search code examples
carrayspointerstoupper

Changing strings to upper within a double pointer array


I need to convert arguments given at command line such as: $ myprogram hello world

and the words need to be printed in CAPS. I am able to to do everything except access the double pointer array to make the changes with toupper()

static char **duplicateArgs(int argc, char **argv)
{
    char **copy = malloc(argc * sizeof (*argv));
    if(copy == NULL){
        perror("malloc returned NULL");
        exit(1);
    }

    int i;
    for(i = 0; i<argc; i++){
         copy[i] = argv[i];   
    }
    char **temp;
    temp = &copy[1];
    *temp = toupper(copy[1]); 

    return copy;
}

Solution

  • *temp = toupper(copy[1]);
    

    toupper converts a single character, if you want to convert an entire string:

    char *temp = copy[1]; /* You don't need a double pointer */
    size_t len = strlen(temp);
    
    for (size_t i = 0; i < len; i++) {
        temp[i] = toupper(temp[i]); 
    }