I'm trying to modify a portion of a program which currently takes user input during runtime and saves the response to a reference to a variable and instead make it fetch the response as an argv[] when compiling. I can fetch the response from argv, but i'm not sure how to retain the variable reference functionality.
Here is the original code:
printf("\n Enter Variable : ");
scanf("%d",&variable);
Output:
PID BURST ARRIVAL 0 0 12
1 2 4
2 3 1
3 4 2
Enter quantum time : 5
0 2 3 3 7 1 9
Average waiting time = 0.00
Average turn-around = 2.25.
Here is what I have attempted:
variable = argv[1];
Output:
0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 3 0 1
And:
&variable = argv[1];
Also:
(int*)&variable = argv[1];
The first attempt compiles and runs with the command line input, but the output from the program is broken/different from the original. The second and third attempts give gcc errors about using & as the left operand. Does anyone know how to mimic the original functionality with argv[] instead of scanf()?
scanf
is both reading the string and converting it to an integer (the %d
). When you use argv[1]
, you only have the string, but haven't converted it to an integer. You need to use a function like atoi
or strtol
, like:
variable = strtol(argv[1], NULL, 10);
Or, as @JohnBollinger correctly points out, sscanf also works:
sscanf(argv[1], "%d", &variable);
If you're trying to convert the command line argument to an integer, then I think the functionality you're looking for is in atoi
or strtol
. But a near drop-in replacement for scanf
is sscanf
, which reads from a string instead of the standard input.
sscanf(argv[1], "%d", &variable);
The reason your first attempt didn't work is because what you're really doing is converting the char*
pointer to an integer. It's not actually reading the content of the string. You were seeing the value of the pointer converted to an int
.
Your other two didn't work because &variable
is not an lvalue and cannot be assigned to.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.