473,789 Members | 2,408 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Argument Processing


Hello,

I'm trying to learn how command line arguments are handled in C. The
following code segment that I wrote as a test program compiles, but when
I try to run it, it core dumps. This is under a FreeBSD environment.
What am I doing wrong here?

/*

just echos the command line arguments onto the screen
tests the format of argument processing

*/

#include <stdio.h>
#include <string.h>
int main(int argc, char argv[])
{
int i; /* generic counter */

printf("argc = %d", argc);
for (i = 0; i <= argc; i++)
{
printf("argv[%d] = %s\n", i, argv[i]);
}

/* return to operating system */
return(0);
}
--
Daniel Rudy

Email address has been encoded to reduce spam.
Remove all numbers, then remove invalid, email, no, and spam to reply.
Nov 14 '05
23 2182
In <kf************ *@alumnus.calte ch.edu> Tim Rentsch <tx*@alumnus.ca ltech.edu> writes:
Just a question - were parentheses EVER required on a 'return'
statement in C?


http://www.lysator.liu.se/c/bwk-tutor.html

What if we wanted count to return a value, say the number of
characters read? The return statement allows for this too:

int i, c, nchar;
nchar = 0;
...
while( (c=getchar( )) != '\0' ) {
if( c > size || c < 0 )
c = size;
buf[c]++;
nchar++;
}
return(nchar);

Any expression can appear within the parentheses.

This is a strong implication that, by the time this tutorial was written,
4 years before K&R1, returning a value *required* the parentheses.

Even K&R1 consistently uses them when returning values, although the
syntax specification in Appendix A doesn't require them. It must have
been a very recent change to the language syntax.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Currently looking for a job in the European Union
Nov 14 '05 #21
"Mike Wahler" <mk******@mkwah ler.net> wrote in message news:<bU******* ***********@new sread1.news.pas .earthlink.net> ...
"Daniel Rudy"
<i0************ *************** *******@n0o1p2a 3c4b5e6l7l8s9p0 a1m2.3n4e5t6>
wrote in message news:kG******** ***********@new ssvr21.news.pro digy.com...

Thanks to everyone who replied. The code now looks like this:

strata:/home/dcrudy/c 1047 $$$ ->cat argtest.c
/*

just echos the command line arguments onto the screen
tests the format of argument processing

*/

#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
int i; /* generic counter */

if (argc < 3)
{
printf("error: need more arguments.\n");
return(0);
}
printf("argc = %d\n", argc);
for (i = 0; i < argc; i++)
{
printf("argv[%d] = %s\n", i, argv[i]);
}

/* return to operating system */
return(0);
}
So now when I run it, instead of core dumping, I get the following output:

strata:/home/dcrudy/c 1046 $$$ ->./argtest arg1 arg2 arg3
argc = 4
argv[0] = ./argtest
argv[1] = arg1
argv[2] = arg2
argv[3] = arg3

Now there is something about this that I do not understand. What
exactly is the nature of argv? I know it's an array,


Actually, it's not. Arrays cannot be passed to or returned
from functions.
but is it an array
of char?


No. It's a pointer (to an array of pointers (to char)).
This allows for arguments of varying lengths.


Actually, it's just a pointer to pointer to char, not a pointer to an
array of pointers to char (otherwise it would have to be typed char
*(*argv)[SIZE]).
A number of people pointed out that the * was required.
AFAIK, * is a pointer reference.


Right. Logically speaking, you're passing an array of strings to
main(). Physically speaking, this translates as a pointer to a
pointer to char:

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

or

int main (int argc, char **argv)

Here's why. Remember that a "string" in C is a 0-terminated array of
char:

char a[6] = "Hello"; /* a == {'H', 'e', 'l', 'l', 'o', 0} */

Therefore, an array of strings would be an array of 0-terminated
arrays of char:

char b[2][6] = {"Hello", "World"};

Now, remember that when you pass an array as an argument to a
function, what actually happens is that you pass a *pointer* to the
first element of the array. In other words:

void foo(char *arr) {...}
....
foo(a); /* a == &a[0] */
foo(b[0]); /* b[0] == &b[0][0] */
foo(b[1]); /* b[1] == &b[1][0] */
....

Even though the actual *types* of a, b[0], and b[1] are "6-element
array of char", when an array identifier appears in any context other
than as an operand to sizeof, it is evaluated as a pointer to the
first element in the array.

Now, since b is itself an array of something, when we pass it to a
function, we are actually passing the pointer to the first element:

void bar(char **arr) {...}
....
bar(b); /* b == &b[0] */
....

In the context of a function prototype, a[] and *a are equivalent;
both indicate that a is a pointer to something. *b[] and **b are also
equivalent. Since this tends to cause no end of confusion, I stick
with the *a, **b syntax exclusively.
Nov 14 '05 #22
"Mike Wahler" <mk******@mkwah ler.net> wrote:
"Nils O. Selåsdal" <NO*@Utel.no> wrote:
Daniel Rudy wrote:
What exactly is the nature of argv? I know it's an array,


argv is char *argv[] .A n array, of pointers to char.


No, 'argv' is *not* an array, it's a pointer.
Think of it as an array of pointers to C strings.


No. It's a pointer to such an array.


If we're going to this level of ped^H^H^H detail,
it's actually a pointer to the first item of such an array.
Nov 14 '05 #23
Da*****@cern.ch (Dan Pop) writes:
In <kf************ *@alumnus.calte ch.edu> Tim Rentsch <tx*@alumnus.ca ltech.edu> writes:
Just a question - were parentheses EVER required on a 'return'
statement in C?


http://www.lysator.liu.se/c/bwk-tutor.html

What if we wanted count to return a value, say the number of
characters read? The return statement allows for this too:

int i, c, nchar;
nchar = 0;
...
while( (c=getchar( )) != '\0' ) {
if( c > size || c < 0 )
c = size;
buf[c]++;
nchar++;
}
return(nchar);

Any expression can appear within the parentheses.

This is a strong implication that, by the time this tutorial was written,
4 years before K&R1, returning a value *required* the parentheses.

Even K&R1 consistently uses them when returning values, although the
syntax specification in Appendix A doesn't require them. It must have
been a very recent change to the language syntax.


This combination of observations explains a lot. Thanks Dan.
Nov 14 '05 #24

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

Similar topics

1
1637
by: Olaf Meding | last post by:
What does the below PyChecker warning mean? More importantly, is there a way to suppress it? PyChecker warning: ..\src\phaseid\integration.py:21: self is argument in staticmethod My best guess is that the warning is related to PyChecker not supporting C++ extensions.
1
3650
by: Patrick Rammelt | last post by:
Hi After upgrading my compiler (gcc-3.3.3 to gcc-4.0.0) I stumbled over an error that I do not understand. Maybe it is a compiler bug, but maybe I can get some new insights from this. Here is a small example: ------------------------------------------------------------------ template <class T> class A { public:
10
2992
by: Richard Heathfield | last post by:
I was recently asked whether it is legal to start processing a variable argument list a second time, /before/ you've finished with it the first time. (I have no idea why the questioner might want to do this, I'm afraid. Since he's normally fairly bright, I presume he had a good reason for asking.) The following code illustrates the point, I think (but don't use it as a va_arg tutorial!, as it kinda assumes there are at least six args...
19
4261
by: Ross A. Finlayson | last post by:
Hi, I hope you can help me understand the varargs facility. Say I am programming in ISO C including stdarg.h and I declare a function as so: void log_printf(const char* logfilename, const char* formatter, ...); Then, I want to call it as so:
6
8844
by: Sunny | last post by:
Hi, I have a very serious issue at hand. I have created a small C# Console App (Csd.exe) that collects a list of files as its argument and generates their Md5 sets. This application is used by other applications in my dept, which simply call this Csd.exe app and passing a list of files. I want to ask how can I return a value from this Csd.exe application as an indicator or a signal to the calling app that Csd.exe has finished working....
4
4651
by: MattBell | last post by:
I've tried to search for an answer to this without much success, and I think it's probably a common thing to do: I have a web service I want to accept an XmlDocument as an argument which conforms to a specific XSD that is defined. Right now when I declare XmlDocument as my argument, it puts the old xml:any type in. How do I change that to reflect the XSD that I'm looking for? Thanks for any Help!
3
3407
by: matko | last post by:
This is a long one, so I'll summarize: 1. What are your opinions on raising an exception within the constructor of a (custom) exception? 2. How do -you- validate arguments in your own exception constructors? I've noticed that, f.ex., ArgumentException accepts null arguments without raising ArgumentNullException. Obviously, if nothing is to be supplied to the exception constructor, the default constructor should
2
2177
by: Nathan Sokalski | last post by:
I have a DataList in which the ItemTemplate contains two Button controls that use EventBubbling. When I click either of them I receive the following error: Server Error in '/' Application. -------------------------------------------------------------------------------- Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/in configuration or <%@ Page EnableEventValidation="true"...
4
3296
by: istillshine | last post by:
I have a function foo, shown below. Is it a good idea to test each argument against my assumption? I think it is safer. However, I notice that people usually don't test the validity of arguments. For example, #define MAX_SIZE 100000 int foo(double *x, unsigned ling sz, int option) {
0
9506
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10404
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10193
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...
1
10136
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9979
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...
1
7525
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5415
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
4089
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
3695
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.