Search code examples
carraysstringgeneric-programming

Copying a char array to another const char array during declaration


What I am trying to do is take a string pointed to by argv[1] and copy it into another array, but I want this new array to be const.

Is there a way to declare the array as const and initialize it with the contents of argv[1] on the same line?

The problem I'm having is that I can't declare it as const and then on the next line copy the string over using strcpy or some such function. That's invalid.

What's the best course of action?


Solution

  • You could do something like this:

    #include <stdio.h>
    
    int main(int argc, char *argv[])
    {
        const char *argument = argv[1];
        printf("%s\n", argument);
    
        return 0;
    }
    

    leveraging the fact that argument[0] is substantially the same of *argument. But beware!

    int main(int argc, char *argv[])
    {
        const char *argument = argv[1];
        printf("%s\n", argument);
    
        argument[2] = 'z';    //ERROR
        printf("%s\n", argument);
    
        return 0;
    }
    

    this above causes an error as expected. But...

    int main(int argc, char *argv[])
    {
        const char *argument = argv[1];
        printf("%s\n", argument);
    
        argv[1][2] = 'z';     //same memory location but no errors
        printf("%s\n", argv[1]);
    
        printf("%s\n", argument);
    
        return 0;
    }
    

    causes no error .... in fact in the last printf you can see that your string has been edited.