Zeeshan Ali
Zeeshan Ali

Reputation: 2261

Store Command Line arguments in a character array on Linux

i am new on Linux. I want to ask that how to store a command line argument in a character array. I am using the following code from an hour but I am unable to solve this problem(Segmentation fault Core Dumped). Here is the code

int main(int argc, char **argv[]) {
    char * MyIp[15];
    int j = 0;
    while(argv[1][j] != '\0') {
        MyIp[j] = argv[1][j++];
    }
    printf("IP : %s\n", *MyIp);
    return 0;
}

and command line argument

./code.o "127.0.0.1"
Segmentation fault(core dumped)

Upvotes: 0

Views: 1056

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409196

There are many problems with the small code you shown. First of all you declare MyIp to be an array of pointers to char, i.e. an array of strings. You assign to it from argv[1][j++] which is a single character, and when printing you print *MyIp as a string (which it is declared as) but the problem here is that the pointer you print (MyIp[0]) is initialized by a character and it's not a very valid pointer.

What you seem to want is to copy the single string argv[1], in which case there are much simpler methods, like e.g. strncpy which were made to copy strings with specific lengths:

char MyIp[15];
if (argc > 1)
{
    strncpy(MyIp¸ argv[1], 14);
    MyIp[14] = '\0';  // If `argv[1]` is too long, terminate manually
}
else
    strcpy(MyIp, "Unknown");

printf("IP : %s\n", MyIp);

Upvotes: 1

Related Questions