user1161080
user1161080

Reputation: 175

passing arguments to main

I know this is fairly basic, but I'm still stuck. So I have a function that needs to take in a variable n, so this is my main function

int main(int argc, char* argv){
  sort(argv[1]);
    }

And I'm calling the program like this:

    ./sort 4 <text.txt

But the number 4 doesnt get recognized or passed into the function. What am I doing wrong? I know that argv[0] should hold the name of program itself and each one from there on should hold the arguments.

Upvotes: 1

Views: 9192

Answers (3)

J&#246;rg Beyer
J&#246;rg Beyer

Reputation: 3671

As described by other you know how to get all argument, but not the "<text.txt".

This is not an argument to your program, but to the shell. This is input redirection, meaning that the input of the file is coming to the program as if it come from stdin (the keyboard).

To prevent this, just call you program like this:

./sort 4 text.txt

I am not sure what the function "sort" is, that you are calling.

Upvotes: 0

Rickard
Rickard

Reputation: 7277

You should try to print them all.

#include <stdio.h>

int main(int argc, const char *argv[])
{
    int i = 0;
    for (; i < argc; ++i) {
        printf("argv[%d] = '%s'\n", i, argv[i]);
    }
    return 0;
}

Running that code with ./a.out 4 < /somefile gives me:

argv[0] = './a.out'
argv[1] = '4'

Eventually you'll have to remember that the '4' is a pointer to an array of characters, and you might have to parse it into an integer.

Upvotes: 7

fnl
fnl

Reputation: 2239

char *argv is not correct. You get passed an array of char* ("Strings"), so the correct way to declare main would be int main(int argc, char *argv[]) or equivalently int main(int argc, char **argv) (in the latter case the array-argument is effectively converted to a pointer to the first element of the array).

What you are retrieving in the current version of the code is the second char in the array of argument-pointers given to you by the environment reinterpreted as an array of characters, which is something else entirely.

Upvotes: 3

Related Questions