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;
}
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.
Related
int i,*ip;
main()
{
i=5;
ip=&i;
*ip=&ip,printf("%d",i);
}
Why does this code "prints" nothing ? it actually works and doesnt give an error.
edit : Actually this code prints something like 635435 which ,I think, may be the address of ip but when ı use -pedantic-errors flag this give me an error so what should I say about the code ? this prints the address of ip or gives an error.
The statement *ip=&ip is not correct as first *ip=&ip is performed and *ip means 5 and that 5 got replaced with address of ip. It should be
ip = (int*)&ip;/* need to typecast as you are assigning address of pointer
to pointer variable which is not advisable */
your code looks like
int i,*ip;
int main(void) { /* side note use int main() instead of just main() */
i=5;
ip=&i;
ip=(int*)&ip,printf("%d\n",i);
return 0;
}
Also use int main(void) instead of just main() as C spec says
It shall be defined with a return type of int and with no parameters:
int main(void) { /* ... */ }
or with two parameters (referred to here as argc and argv, though any names may be used, as they are local
to the function in which they are declared):
int main(int argc, char *argv[]) { /* ... */ }
In C, how can I produce an error if no arguments are given on the command line? I'm not using int main(int argc , * char[] argv). my main has no input so I'm getting my variable using scanf("%d", input)
Your question is inconsistent: if you want to get arguments from the command line, you must define main with argc and argv.
Your prototype for main is incorrect, it should be:
int main(int argc, char *argv[])
If the program is run without any command line arguments, arc will have the value 1. You can test it this way:
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("error: missing command line arguments\n");
return 1;
}
...
}
If you define main with int main(void) you have no portable access to command line arguments. Reading standard input has nothing to do with command line arguments.
Given the code:
#include <stdio.h>
int main() {
int input;
int rc = scanf("%d", &input);
}
We can verify that scanf() was able to successfully get some input from the user by checking its return value. Only when rc == 1 has the user properly given us valid input.
If you'd like to know more, I recommend reading scanf's documentation.
well, the definition of your main arguments are as follow:
argc is the number of arguments
argv are the argument strings
This means you only need to check if argc is equal to one (the program name only) and output an error ;-)
If you use int main() only, you have no way to know.
I'm trying to printf an integer that was passed by command line but the console print a long random values.
I put this into RUN "C:\Users\pc\Documents\Visual Studio 2013\Projects\Lab3\Debug\Lab3.exe randomString 4"
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char *argv[]){
printf("%s\n", argv[0]); // Working
printf("%s\n", (argv[1])); // working
printf("%d\n", (int)(argv[2])); // NOT Working
printf("%d\n", argc); // Working
system("pause");
return 0;
}
You can't just "cast" a char* pointer to an int and expect it to be magically converted. That is just printing the address of the first element of the array. You need to convert it to an int with a runtime function such as atoi(argv[2]) See function details here
The argv[2] variable is a string pointer (char* to be precise). So casting it to int will just give you the numerical value of this pointer (or part of it, depending on the size of the addresses on your system). And this is exactly your "random long number" that you are seeing. In order to convert the string to a number you can use functions like atoi.
I've written a code that sums up integers brought in from the command line:
#include <stdio.h>
int main(int argc, int* argv[]) {
int i, s=0;
for (i=1;i<argc;i++)
s=s + *argv[i];
printf("Sum: %d\n", s);
return 0;
}
The best part is, it passes the gcc compiling process, but when I actually run it and insert the numbers, the result seems I somehow breached the range of int.
It seems that you are compiling your code in C89 mode in which s is taken as int by default by compiler. s is uninitialized therefore nothing good could be expected. If fact it will invoke undefined behavior.
Note that argv[i] is of char * type (change your main signature) and you need to convert it to int before adding it to s.
The 2nd argument of main should be either of type char** or of type char*[] and not int*[]. So, *argv[i] is of type char. Instead of getting each character, you can get each string(argv[i] which is of type char*) and then extract the number from it and assign it to a variable, say num. This can be done by using the sscanf function:
#include <stdio.h>
int main(int argc, char* argv[]) { //int changed to char here
int i, s=0,num;
for (i=1;i<argc;i++)
if(sscanf(argv[i],"%d",&num)) //if extraction was successful
s=s + num;
printf("Sum: %d\n", s);
return 0;
}
Assuming you have s initialized properly as shown below.
Along with this the prototype of your main() should be as shown below inorder to get the command line arguments.
int main(int argc, char **argv)
{
int s =0;
// Check for argc matches the required number of arguments */
for(i=1;i<argc;i++)
s=s + atoi(argv[i]); /* Use atoi() to convert your string to integer strtol() can also be used */
printf("%d\n",s);
return 0;
}
PS: Using uninitialized variables lead to undefined behvaior
So, this is a really basic question. For an assignment we had to write a c program that would calculate the page and offset number of a virtual address. My program seems to work fine when I make a vocal variable of the virtual address that we are supposed to do calculations on, but I can't figure out how to pass it.
The assignment says that we should run our program like this
./program_name 19982
I just can't figure out how to pass that 19982 in terminal on my mac. Any help is appreciated. (And in before someone makes a mac joke.)
It sounds like you are looking for argv, which I suppose is difficult to search for if you don't know what it is called! This isn't specific to Mac OS X's Terminal.
The argv argument of a main() function is an array of strings; its elements are the individual command line argument strings.
The path to the program being run is the first element of argv, that is argv[0].
The number of elements in argv is stored in argc:
#include <stdio.h>
int main(int argc, char* argv[])
{
int arg;
for (arg = 0; arg < argc; ++arg)
{
printf("Arg %d is %s\n", arg, argv[arg]);
}
return 0;
}
Compile:
% gcc program_name.c -o program_name
Run:
% ./program_name 19982
Arg 0 is ./program_name
Arg 1 is 19982
Converting argv[1] to an int is left as an exercise.
You can use argc and argv to access program's arguments. argc is the "arguments count" - the number of arguments passed. argv is the "arguments vector", where the first member is the name of the program.
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char* argv[] )
{
int Address;
if (argc > 1)
{
Address = atoi(argv[1]);
}
else
{
printf("No arguments passed\n");
return 1;
}
return 0;
}
Typically, you'd use "argv/argc" in main. For example:
#include<stdio.h>
int
main (int argc, char *argv[])
{
if (argc < 2)
printf ("You didn't enter any arguments\n");
else
printf ("Your first argument is %s\n", argv[1]);
return 0;
}
Under Linux, you'd compile and run like this:
gcc -o hello hello.c
./hello howdy!
Again under Linux, it would output something like this:
Your first argument is howdy!
All C (and C++, don't know about objective-c) programs start their execution in the function main. This function takes two arguments: An integer, usually named argc which is a counter of the number of arguments given to the program; The second function argument is an array of char pointers, usually called argv and is the actual command line arguments.
The first entry in argv is always the name of the command itself, which means that argc will always be at least 1.
The following program prints all arguments given on the command line:
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("Total number of values in argv: %d\n", argc);
for (int a = 0; a < argc; a++)
printf("argv[%02d]: %s\n", a, argv[a]);
}