I am writing a program that has to use the strcmp function using a pointer in the main. There cannot be any user input. There is no menu, it must execute the arguments as parameters in the main function. my question is am I calling the strcmp function proper?
int main(int n, char **p, char **choice)
{
int i, x, A[100];
if (strcmp(*choice, "mode")==0){
Your code will compile and is grammatically correct, but I'm not certain that the logic is what you want it to be.
Typically main
has 2 or 3 arguments, usually written as int argc, char **argv, char ** envp
(if there are only 2, it's the first 2). It's ok to rename them as you did, to n, p, and choice, but you need to know what each of them mean.
argc
("n") is the number of strings in the argv
array, 0 indexed. There will always be at least 1 argument - the name of the program. Arguments passed on the command line start at argv[1]
.
argv
is all of the arguments, including the program name. The array will go from 0 to argc
- 1
envp
is an array of strings listing all of the environment settings. It is terminated with a NULL entry as its final one.
If you're tasked with executing the arguments as parameters, you're likely to be interested in looping through the strings in argv. You'll want something like this:
int i = 1;
for (i = 1; i < argc; ++i) {
if (strcmp(argv[i], "mode") == 0) {
Of course, if you want to keep your variable names, just replace them:
int i = 1;
for (i = 1; i < n; ++i) {
if (strcmp(p[i], "mode") == 0) {
So, yes. Your use of strcmp
was syntactically acceptable. But it likely doesn't do what you want.
Good luck!
Incidentally, if you ever need to loop through envp, you'd do so as follows:
int i = 0;
while (envp[i] != NULL) {
if (strcmp(envp[i], "mode") == 0) { // or whatever else you needed to do.
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.