0

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)
1
  • Why have you tagged it "java"? Commented May 25, 2015 at 7:22

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.