473,888 Members | 2,199 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Weird pointer arithmetic on argv - How can it work??

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, "incompatib le types
in assignment" on that second line. Why does it work for them, but it
doesn't work for me?

Thanks!

Jerry Krinock

Oct 15 '06 #1
5 3185
>I need to modify the code of a command-line tool. The source code
>starts out like this:

int main(int argc, char *argv[])
char *argv[] in this context (function parameter) really means the
same as 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).
Correct. It's skipping over the flag arguments. argv is a
pointer-to-pointer, and you're advancing it by optind pointers.
Knowing the way the non-standard function getopt() is supposed to
work, it won't go out of range of the array.

>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.
Of course a (char *) *DOES* have a constant size (it's often 32 or
64 bits). argv is an array of pointers, and char * pointers have
a constant size. The strings pointed at do not have constant size,
but they aren't *in* the array.
>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 ;
argv has char ** type. You can only declare it as char *argv[] if
it's a function parameter, which is equivalent to char ** (when it's
a function parameter). You cannot increment an array name, which is
a problem if you declare it as char *argv[] as a local variable.

char *av[4];
char **argv = av;
/* somehow you initialize av here */
argv += optind;
>the compiler complains, rightfully so I would say, "incompatib le types
in assignment" on that second line. Why does it work for them, but it
doesn't work for me?
Oct 15 '06 #2
je***@sheepsyst ems.com writes:
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).
A char* does have a constant size.

C doesn't actually have array parameters. In a parameter list,
"char *argv[]" really means "char **argv", so argv is a pointer to
pointer to char. (Presumably the pointer-to-char that argv points
to is the first element of an array of pointers-to-char.)

C allows the "[]" syntax here for "convenienc e, but in my opinion it
just causes confusion.

I suggest reading section 6 of the comp.lang.c FAQ,
<http://www.c-faq.com/>.
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, "incompatib le types
in assignment" on that second line. Why does it work for them, but it
doesn't work for me?
Outside a parameter list, "char *argv[4];" really does declare an
array, not a pointer.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Oct 15 '06 #3

je***@sheepsyst ems.com wrote:
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).
That's precisely what it's doing.
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.
On my machine, sizeof(char *) returns 4. I suspect a 64 bit machine
would return 8. While the array it points to may not have a size known
at compile time, the pointer itself has a set size. Remember: a
pointer's just an integer.
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:
Well that's what argv is. I suggest you pick a new name for your array,
for the sake of anybody that might maintain your program.
char* argv[4] ;
argv += optind ;

the compiler complains, rightfully so I would say, "incompatib le types
in assignment" on that second line. Why does it work for them, but it
doesn't work for me?
char* argv[4] is an array of four char pointers. You can't perform
pointer arithmetic on an array.
As to why it works for them, it's because as a parameter, a[] is
equivalent to *a. (You can't pass actual arrays in C.)
Thanks!

Jerry Krinock
Oct 15 '06 #4
je***@sheepsyst ems.com wrote:
>
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? ...
Who knows. getopt() is not a standard C routine, and you failed to
show its source. You also failed to declare optind.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net>

Oct 15 '06 #5
Thank you, guys. I understand it now and have my program working.

Oct 15 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
6966
by: a | last post by:
I am having trouble understanding the results of the following code: #include <iostream> using namespace std; int main(int argc, char* argv) { unsigned short *IO = reinterpret_cast<unsigned short*>(0x8000); unsigned short offset = static_cast<unsigned short>(0x2);
8
2196
by: ceo | last post by:
Hi, Following is a program that doesn't give the expected output, not sure what's wrong here. I'm adding the size of derived class to the base class pointer to access the next element in the array. Why does bp point to some address that is not &d? Please clarify. Thanks,
22
12764
by: Alex Fraser | last post by:
From searching Google Groups, I understand that void pointer arithmetic is a constraint violation, which is understandable. However, generic functions like qsort() and bsearch() must in essence do exactly this, and similarly generic functions seem to have useful applications. In a few posts I read, it was suggested to avoid void pointer arithmetic by casting to a char pointer, and performing arithmetic on that (in multiples of...
1
1652
by: Pieter Claassen | last post by:
Ok, I have something that works, but I don't understand why. I use libpcap to get data of the wire and then initially I casted the packet to ethernet, then marched along the memory in chunks of bytes for the length of the ethernet header until I reached the IP header and so forth... So, I changed my code and now process the ethernet header after which I pass the size of the the ethernet header to be deducted and a pointer to the the...
22
4831
by: Christopher Benson-Manica | last post by:
Is adding 0 to a pointer to non-void that is equal to NULL legal? int *p=NULL; p+=0; -- Christopher Benson-Manica | I *should* know what I'm talking about - if I ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
6
2299
by: Francois Grieu | last post by:
Are these programs correct ? #include <stdio.h> unsigned char a = {1,2}; int main(void) { unsigned char j; for(j=1; j<=2; ++j) printf("%u\n", *( a+j-1 )); return 0; }
3
2214
by: randomtalk | last post by:
hello everyone! Well, recently i've been trying to pick up c and see what is pointer all about (been programming in lisp/python for the better part of my last two years).. mmm.. I'm currently reading The C Programming Language Second Edition.. When i hit on pointer arithmetic example, i have no idea what's happening, hopefully some of you could alleviate my confusion, so here goes:
26
3077
by: Bill Reid | last post by:
Bear with me, as I am not a "professional" programmer, but I was working on part of program that reads parts of four text files into a buffer which I re-allocate the size as I read each file. I read some of the items from the bottom up of the buffer, and some from the top down, moving the bottom items back to the new re-allocated bottom on every file read. Then when I've read all four files, I sort the top and bottom items separately...
8
1913
by: subramanian100in | last post by:
Supoose we have, int x; int *p = &x; int *q; q = p + 1;
0
9957
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10772
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10434
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9593
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
7143
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5810
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4635
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4239
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3245
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.