0

Suppose we have this main:

int main(int argc,char *argv[]){

}

How could I manage to get the elements of *argv[],in order to extract some statistics off of each one(e.g letter count,numbers ,etc.)?

I have tried couple of things but didn't work(using pointers ).Eventually I tried a work-around,using strcpy() to copy each element of the array and that worked. So my question is,are there other ways to achieve that?

Here's an example of my code that works:

int main(int argc,char *argv[]){
    char temp[50];
    strcpy(temp,argv[1]); //extracting the first element of the array.

Paner
  • 20
  • 4
  • You should show us what (and how) *didn't* work, not what worked. – Eugene Sh. Feb 08 '22 at 15:35
  • "How could I manage to get the elements of `*argv[]`" - https://stackoverflow.com/questions/3024197/what-does-int-argc-char-argv-mean – ForceBru Feb 08 '22 at 15:36
  • We don't understand the difficulty. Where is it that you use `temp` where using `argv[1]` directly doesn't work? – Joshua Feb 08 '22 at 15:37
  • @Joshua How could I iterate through the each character of the argv[1] ? The point of me using strcpy() was to achieve that. – Paner Feb 08 '22 at 15:39
  • `argv[1][8]` would be the 9'th character of `argv[1]` (if exists) – Eugene Sh. Feb 08 '22 at 15:42
  • @EugeneSh. That was what I was looking for. I Knew it would be something simple that i was missing.Even though I got it working,I was wondering how it can be done without using strcpy(). I didnt think the way to access a char was like a 2D array(if that is the correct way of describing it) .You can post it as an answer if you want,and I will vote for solved as soon as I can.Thanks! – Paner Feb 08 '22 at 15:50
  • 1
    @SergeBallesta: On what platform are they `const`, because I've heard of no such thing; but rather on C's origin platform they were intended to be written to and some programs used that in a way that duplicating `argv` wouldn't have worked; and the other major platforms emulated the ability to write to them even though they didn't provide the behavior involved. – Joshua Feb 08 '22 at 15:55
  • @SergeBallesta I'll keep that in mind,hopefully strdup is available(I'm using Unix/Posix systems). – Paner Feb 08 '22 at 15:56

1 Answers1

0

Another way of doing so is as below:

int main(int argc,char argv[]){
char *temp = argv;
}

This code will create a string named "temp" which is a copy of "argv[]". You can use to extract any stats you like without having to use the "strcopy" function. Also, take note that I have changed the argument from int main(int argc, char *argv[]) to int main(int argc, char argv[])

Om Kaushik
  • 21
  • 3