QUESTION 15
What do argc and argv represent?
2 marksAnswer
argc gives the number of argument strings, and argv points to them. argv[argc] is a null pointer. When argc is positive, argv[0] represents the program name or an empty string.
QUESTION 15
argc gives the number of argument strings, and argv points to them. argv[argc] is a null pointer. When argc is positive, argv[0] represents the program name or an empty string.
QUESTION 16
Command-line arguments let a user supply input when starting a program rather than through later keyboard reads.
int main(int argc, char *argv[])The example requires exactly two user-supplied numeric strings, so it checks argc == 3 before using argv[1] and argv[2]. Accessing a missing argument is invalid. The shell’s quoting rules affect how spaces are grouped before the program receives its arguments.
Use strtol with an end pointer and errno checking. A successful conversion must consume at least one character, end at the string terminator and avoid ERANGE. Then check the application range before converting to int. atoi does not provide the same reliable error-reporting interface.
Running the compiled program with arguments 12 and 8 prints Sum = 20. Supplying abc or an unsupported value reports invalid arguments. The sample accepts values from -10000 through 10000, making their sum safe even within the minimum int range required by C.
Parsing strings of lengths m and n takes O(m + n) character work. The program needs only fixed conversion variables. The online single-file compiler may not expose a command-line-argument field; use a terminal with the shown compile/run command when that option is unavailable.
/* CodeBhavya | Data Structures AR25 | Learning example */
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int read_number(const char *text, int *out)
{
char *end;
errno = 0;
long value = strtol(text, &end, 10);
if (end == text || *end != '\0' || errno == ERANGE || value < -10000 || value > 10000) { return 0; }
*out = (int)value;
return 1;
}
int main(int argc, char *argv[])
{
int a, b;
if (argc != 3 || !read_number(argv[1], &a) || !read_number(argv[2], &b)) {
puts("Usage: program integer integer (-10000..10000)"); return 1;
}
printf("Sum = %d\n", a + b);
return 0;
}gcc -std=c11 -Wall -Wextra -pedantic main.c -o program
./program 12 8In Windows PowerShell, use program.exe as the output name and .\program.exe to run it.
The example uses values in the code and the shown command-line arguments.
Sum = 20