Brian Jarcus
Brian Jarcus

Reputation: 69

Can't accept multiple command line arguments and assign to variable

I am learning C and I am not used to pointers and the way C handles strings. I am trying to create a program that accepts multiple command line arguments and assigns them to variables so that I can later use them. I can get the program to accept the first argument and assign it as a int. But when I try to accept the second argument I get a SEGMENTATION FAULT. I have tried testing by removing the second variable (service) and then assigning port to argv[2] and it doesn't work. It is something about accepting the second argument that the compiler does not like but I am not able to figure it out.

#include <stdio.h>

int main(int argc, char *argv[]) {
    int port = atoi(argv[1]);
    char service = argv[2];   
   return 0;
}

Upvotes: 2

Views: 568

Answers (1)

Matt Goodrich
Matt Goodrich

Reputation: 5095

When you write char service = argv[2];, you are assigning a char pointer to a char. You know argv is a char pointer array, because you define it as char *argv[]. Fix by just adding char *service = argv[2];

So your rewritten code could look like this:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
    if (argc < 3) {
        printf("Requires more arguments");
        return 1;
    }

    int port = atoi(argv[1]);
    char *service = argv[2];   
    printf("%s", service); //From edit
    return 0;
}

You may want to add a check for the value of argc (i.e. argc >= 3), since it will seg fault if there aren't three arguments.

Edit (response to comment):

To print the service, use:

printf("%s", service);

The %s specifies you will print a string of characters (char *) and you simply use service, because you need to specify the pointer.

Edit 2:

If you don't add #include <stdlib.h>, you will receive something along the lines of "warning: implicit declaration of 'atoi' is invalid in C99", which may also produce an error depending on your compiler settings.

Upvotes: 1

Related Questions