You can print the arguments without transferring them into character arrays. They are null-terminated C strings and printf eats them for breakfast:
for (i=0; i<argc; i++)
printf("%s\n", argv[i]);
Answer from David Heffernan on Stack OverflowThis seems to be always included in java's main method, but I still don't understand what it means honestly.
Edit: thanks!
Arguments to main in C - Stack Overflow
c# - Why using string[] args in all main methods? - Software Engineering Stack Exchange
java - What is the "String[] args" parameter in the main method? - Stack Overflow
c# - What is "string[] args" in Main class for? - Stack Overflow
You can print the arguments without transferring them into character arrays. They are null-terminated C strings and printf eats them for breakfast:
for (i=0; i<argc; i++)
printf("%s\n", argv[i]);
Here is example that converts command line arguments to single string:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
if (argc < 1)
return 0;
int i;
int strsize = 0;
for (i=1; i<argc; i++) {
strsize += strlen(argv[i]);
if (argc > i+1)
strsize++;
}
printf("strsize: %d\n", strsize);
char *cmdstring;
cmdstring = malloc(strsize);
cmdstring[0] = '\0';
for (i=1; i<argc; i++) {
strcat(cmdstring, argv[i]);
if (argc > i+1)
strcat(cmdstring, " ");
}
printf("cmdstring: %s\n", cmdstring);
return 0;
}
The signature of main is:
int main(int argc, char **argv);
argc refers to the number of command line arguments passed in, which includes the actual name of the program, as invoked by the user. argv contains the actual arguments, starting with index 1. Index 0 is the program name.
So, if you ran your program like this:
./program hello world
Then:
- argc would be 3.
- argv[0] would be "./program".
- argv[1] would be "hello".
- argv[2] would be "world".
Imagine it this way
*main() is also a function which is called by something else (like another FunctioN)
*the arguments to it is decided by the FunctioN
*the second argument is an array of strings
*the first argument is a number representing the number of strings
*do something with the strings
Maybe a example program woluld help.
int main(int argc,char *argv[])
{
printf("you entered in reverse order:\n");
while(argc--)
{
printf("%s\n",argv[argc]);
}
return 0;
}
it just prints everything you enter as args in reverse order but YOU should make new programs that do something more useful.
compile it (as say hello) run it from the terminal with the arguments like
./hello am i here
then try to modify it so that it tries to check if two strings are reverses of each other or not then you will need to check if argc parameter is exactly three if anything else print an error
if(argc!=3)/*3 because even the executables name string is on argc*/
{
printf("unexpected number of arguments\n");
return -1;
}
then check if argv[2] is the reverse of argv[1] and print the result
./hello asdf fdsa
should output
they are exact reverses of each other
the best example is a file copy program try it it's like cp
cp file1 file2
cp is the first argument (argv[0] not argv[1]) and mostly you should ignore the first argument unless you need to reference or something
if you made the cp program you understood the main args really...
Console applications predate GUI applications, and these take command-line parameters for very long time (at least from CP/M time, which preceded MS-DOS, which preceded Windows, which preceded Windows NT — all preserving more or less the same logic).
You can pass command-line parameters to Windows GUI apps, too.
These are the args.
This is not the sole province of "old" console (command line) applications. Every running program has a "command line" that points at the executable image and includes any command line parameters. Plenty of GUI apps take arguments that alter either their initialization behavior or runtime behavior or both.
Most languages do let you specify an entry-point function that takes no arguments. But virtually all of them also allow you to pass arguments. This args array is simply an ordered collection of whatever is passed on the command line after the name of the executable file when the program is executed. EDIT: And of course in the case of the C language (as one example), the first argument (index 0) is actually the name of the program.
For example, imagine a pointless little program that displays a message in a message box, and lets you specify the message and the title for the window on the command line, like this:
myprogram.exe -title Foo -message Bar
Your args array in this case will look like this, presuming a language like C# which does not include the program name in the args array:
args[ 0 ] = "-title"
args[ 1 ] = "Foo"
args[ 2 ] = "-message"
args[ 3 ] = "Bar"
Making sense of the order of the arguments, and which ones are valid or not, is totally up to your own application code.
In Java args contains the supplied command-line arguments as an array of String objects.
In other words, if you run your program in your terminal as :
C:/ java MyProgram one two
then args will contain ["one", "two"].
If you wanted to output the contents of args, you can just loop through them like this...
public class ArgumentExample {
public static void main(String[] args) {
for(int i = 0; i < args.length; i++) {
System.out.println(args[i]);
}
}
}
The program will print in the terminal:
C:/ java MyProgram one two
one
two
C:/
Those are for command-line arguments in Java.
In other words, if you run
java MyProgram one two
Then args contains:
[ "one", "two" ]
public static void main(String [] args) {
String one = args[0]; //=="one"
String two = args[1]; //=="two"
}
The reason for this is to configure your application to run a particular way or provide it with some piece of information it needs.
If you are new to Java, I highly recommend reading through the official Oracle's Java™ Tutorials.
From the C# programming guide on MSDN:
The parameter of the Main method is a String array that represents the command-line arguments
So, if I had a program (MyApp.exe) like this:
class Program
{
static void Main(string[] args)
{
foreach (var arg in args)
{
Console.WriteLine(arg);
}
}
}
That I started at the command line like this:
MyApp.exe Arg1 Arg2 Arg3
The Main method would be passed an array that contained three strings: "Arg1", "Arg2", "Arg3".
If you need to pass an argument that contains a space then wrap it in quotes. For example:
MyApp.exe "Arg 1" "Arg 2" "Arg 3"
Command line arguments commonly get used when you need to pass information to your application at runtime. For example if you were writing a program that copies a file from one location to another you would probably pass the two locations as command line arguments. For example:
Copy.exe C:\file1.txt C:\file2.txt Further to everyone else's answer, you should note that the parameters are optional in C# if your application does not use command line arguments.
This code is perfectly valid:
internal static Program
{
private static void Main()
{
// Get on with it, without any arguments...
}
}
(String ...) is an array of parameters of type String, where as String[] is a single parameter.
Now here String[] can full fill the same purpose here but (String ...) provides more readability and easiness to use.
It also provides an option that we can pass multiple array of String rather than a single one using String[].
A feature of String[] vs String... is that the "String..." does not need to be part of the call.
public void test(String... args){
if(args.length > 0){
for( String text : args){
System.out.println(text);
}
}else{
System.out.println("No args defined.");
}
}
public void callerTest(){
test();
System.out.println();
test("tree");
System.out.println();
test("dog", "cat", "pigeon");
}
Then if you call callerTest(); the Output will be:
No args defined.
tree
dog
cat
pigeon
In the last lines of your question, what you mention is C being a procedural language. This means, you should split your semantic logic into reusable smaller logical bits and implement smaller portions of your code and implement your program by using the functions you implemented.
Although, as you come from a object-oriented language, I believe you must be familiar with the concepts I mentioned.
Coming to your example, your program consists of a fairly small codebase and it does these things:
- Iterate through the
argvstrings - Combine the
argvstrings in another string
But if I did not misunderstand, your first iteration is to find the count of the arguments. That is what argc variable, therefore your first while loop is unnecessary, you can simply set size = argc - 1;
You have an unnecessary condition check and this part is unnecessary:
strcat(str, argv[1]); // putting the string together
strcat(str, " ");
strcat(str, argv[2]);
strcat(str, " ");
You should start your for loop from 1 instead of 3, and remove these lines.
Your condition check also seems unnecessary, as your for for loop would produce similar results.
Therefore, I would not say that this code is bad due to not being written in procedural paradigm, but it is bad due to overall unnecessary lines of code.
A shorter approach would be:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if(argc == 1) {
printf("ERROR: Expected at least 1 argument\n");
return 0;
}
int i, v = 0, size = argc - 1;
char *str = (char *)malloc(v);
for(i = 1; i <= size; i++) {
str = (char *)realloc(str, (v + strlen(argv[i])));
strcat(str, argv[i]);
strcat(str, " ");
}
printf("%s\n", str);
return 0;
}
Trust the promise.
argcis the Argument Count:int size = 0; while(argv[size]) { // gets the amount of arguments besides the first argument size++; }At this point you may
assert(size == argc);Here be arguments:
int v = strlen(argv[1]) + strlen(argv[2]); // for allocating memroyWe checked
argv[1]. Howeverargv[2]may not be there.int v = strlen(argv[1]) + strlen(argv[2]); // for allocating memroy char *str = (char *)malloc(v); strcat(str, argv[1]); // putting the string together strcat(str, " "); strcat(str, argv[2]); strcat(str, " ");vdoesn't have enough space to accomodate both strings and two spaces and a terminating0.str = (char *)realloc(str, (v + strlen(argv[i]))); // reallocates enough memoryIt doesn't reallocate enough. The subsequent
strcat(str, " ")is not accounted for.