Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 292
LTClipp Avatar asked Aug 24 '26 12:08

LTClipp


2 Answers

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.

like image 192
JoulinRouge Avatar answered Aug 27 '26 04:08

JoulinRouge


Considering you don't want to modify it (it being a const and all), you don't even need to copy it somewhere:

(Basic code lacking sanity checks such as correct argument count and argument lenght)

const char *myPointer = NULL;
myPointer = argv[1];

Now myPointer is pointing to argv[1], your first argument that the program was launched with.

So if you launch your program like myfolder/myexe.exe myArg your myPointer will point to a char array with these contents {'m','y','A','r','g','\0'}

like image 35
Magisch Avatar answered Aug 27 '26 02:08

Magisch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!