J
jerry
I need to modify the code of a command-line tool. The source code
starts out like this:
int main(int argc, char *argv[])
{
int ch, A, B ;
while ((ch = getopt(argc, argv, "AB")) != -1)
switch (ch) {
case 'A':
A = 1;
break;
case 'B':
B = 1 ;
break;
}
argc -= optind;
argv += optind;
What in heaven's name is that last line doing? It seems to be doing
pointer arithmetic, incrementing argv by the current value of optind
(which is an integer, the "ind"ex of the current argument). But I
thought you can only do pointer arithmetic when the size of each array
element is a constant known by the compiler, and of course a char* does
not have a constant size. How can this even compile? (It does).
Furthermore, I want to rewrite this with argv assigned in the code
instead of being a command-line argument, but when I write:
char* argv[4] ;
argv += optind ;
the compiler complains, rightfully so I would say, "incompatible types
in assignment" on that second line. Why does it work for them, but it
doesn't work for me?
Thanks!
Jerry Krinock
starts out like this:
int main(int argc, char *argv[])
{
int ch, A, B ;
while ((ch = getopt(argc, argv, "AB")) != -1)
switch (ch) {
case 'A':
A = 1;
break;
case 'B':
B = 1 ;
break;
}
argc -= optind;
argv += optind;
What in heaven's name is that last line doing? It seems to be doing
pointer arithmetic, incrementing argv by the current value of optind
(which is an integer, the "ind"ex of the current argument). But I
thought you can only do pointer arithmetic when the size of each array
element is a constant known by the compiler, and of course a char* does
not have a constant size. How can this even compile? (It does).
Furthermore, I want to rewrite this with argv assigned in the code
instead of being a command-line argument, but when I write:
char* argv[4] ;
argv += optind ;
the compiler complains, rightfully so I would say, "incompatible types
in assignment" on that second line. Why does it work for them, but it
doesn't work for me?
Thanks!
Jerry Krinock