Reputation: 43
I am working on creating an uppercase function. I want to implement argc and argv arguments in to my code but I don't know how to do it.
Here is my code;
Main.c:
#include <stdio.h>
#include <stdlib.h>
#include "upperc.h"
int main(int argc, char *argv[])
{
char s[] = "HellO2 world3!";
printf("%s \n", s);
printf("%s \n", uppercase(s));
return 0;
}
upper.c:
/*
Parsing the string, then making the letters to uppercase.
*/
#include <stdio.h>
#include "upperc.h"
char * uppercase(char *s) {
for(char *p = s; *p; ++p) {
if ('a' <= *p && *p <= 'z')
*p = *p & ~' ';
}
return s;
}
upper.h:
#ifndef UPPERC_H_INCLUDED
#define UPPERC_H_INCLUDED
char * uppercase(char *s);
#endif // UPPERC_H_INCLUDED
Upvotes: 1
Views: 426
Reputation: 9855
As this looks like some kind of homework, I don't give a full answer.
argc
is the number of arguments including the program name that was executed. That means argc
is 1 if no arguments were specified, 2 if one argument was specified etc.
Don't pass argv[1]
unconditionally to your uppercase
function. This would be undefined behavior if argc
is 1 or even 0. (see below for details)
Depending on your requirements, you should check argc
and process either only argv[1]
if available, which would be the first argument, or process argv[1]
, argv[2]
... in a loop as necessary.
Additional details (for experts, because my original wording was not exact):
If your program is called in a normal way, the value of argc
should be at least 1 and argv[0]
will be the program name. The value of argv[argc]
is a NULL
pointer. Of course you can access the pointer value in this case, but you cannot dereference it, i.e. you cannot access a value where the pointer would be pointing to.
It is possible to call your program in a way that results in an argc
value 0. In this case argv[0]
will be a NULL
pointer, and the array element argv[1]
(and all following it) will be undefined.
See https://en.cppreference.com/w/c/language/main_function
Upvotes: 1