473,651 Members | 2,549 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

passing command line argument to array

Good evening,

I would like to pass the size of an array from the commandline.

int main(int argc, int *argv[]) {
....
max=*argv[1];

int list[max];
....

This does not work, because the size should be a constant.

How can I work around this? I tried const or static, nothing works.

Thank you,

Ernst
May 4 '07 #1
6 6924
In article <f1************ *@news.t-online.com>,
virgincita schmidtmann <do*******@t-online.dewrote:
>I would like to pass the size of an array from the commandline.
>int main(int argc, int *argv[]) {
...
max=*argv[1];
int list[max];
...
>This does not work, because the size should be a constant.
>How can I work around this? I tried const or static, nothing works.
What you propose is not legal in C89, but is (if I understand
correctly) legal in C99 "variable length arrays".

In C89, what you need to do is malloc() the space you need and
store the returned pointer. int *list = malloc(max * sizeof int)
--
Okay, buzzwords only. Two syllables, tops. -- Laurie Anderson
May 4 '07 #2
On Fri, 4 May 2007 22:33:25 +0200, "virgincita schmidtmann"
<do*******@t-online.dewrote:
>Good evening,

I would like to pass the size of an array from the commandline.

int main(int argc, int *argv[]) {
...
max=*argv[1];

int list[max];
Even under a C99 compiler, this will not do what you want. *argv[1]
is, by definition, a character. If it happened to be the character
'2' and you run this on an ASCII system, it will define an array of 50
int. And if the command line argument was the value "75", you would
not allocate enough space. On an EBCDIC system, '2' would produce an
array 242 int.
>...

This does not work, because the size should be a constant.
This is true in C89 but C99 does allow variable length arrays.
>
How can I work around this? I tried const or static, nothing works.
Since you don't have a C99 compiler, the solution is in two parts:

First convert the data argv1 points at to an integer. strtol
would be the method of choice because it provides a convenient method
for error checking.

Second, allocate memory for the desired array and store the
address of this memory in a pointer. malloc is a good choice here.
You can then refer to elements of the array using normal array
notation such as ptr[i].
Remove del for email
May 5 '07 #3
virgincita schmidtmann wrote:
Good evening,

I would like to pass the size of an array from the commandline.

int main(int argc, int *argv[]) {
...
max=*argv[1];

int list[max];
...

This does not work, because the size should be a constant.

How can I work around this? I tried const or static, nothing works.

Thank you,

Ernst

Create a dynamic array with malloc?

int *list;
int max;
max = atoi(argv[1]);
list = malloc(max * sizeof *list);

The above is not a program, it is only a clue. The task is yours.

--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
May 5 '07 #4
Thank you all!

1. Mhmm. If I allocate memory to a pointer, can I use this pointer
without defining an array?

I think, array is a pointer to the first element of the array. Memory
size from malloc and list[] is the same. Does the compiler have to
know the size of an element in the array?

2. In the past I took integer arguments from the commandline by
defining argv[] as int. Well, there is a problem with argv[0], because
it is definitely the name of the program. But if I don't use it?

3. I am not really sure, if I need a variable length array.

However, I will try it.

Best regards,

Ernst

Barry Schwarz wrote:
On Fri, 4 May 2007 22:33:25 +0200, "virgincita schmidtmann"
<do*******@t-online.dewrote:

>>Good evening,

I would like to pass the size of an array from the commandline.

int main(int argc, int *argv[]) {
...
max=*argv[1];

int list[max];


Even under a C99 compiler, this will not do what you want. *argv[1]
is, by definition, a character. If it happened to be the character
'2' and you run this on an ASCII system, it will define an array of 50
int. And if the command line argument was the value "75", you would
not allocate enough space. On an EBCDIC system, '2' would produce an
array 242 int.

>>...

This does not work, because the size should be a constant.


This is true in C89 but C99 does allow variable length arrays.

>>How can I work around this? I tried const or static, nothing works.


Since you don't have a C99 compiler, the solution is in two parts:

First convert the data argv1 points at to an integer. strtol
would be the method of choice because it provides a convenient method
for error checking.

Second, allocate memory for the desired array and store the
address of this memory in a pointer. malloc is a good choice here.
You can then refer to elements of the array using normal array
notation such as ptr[i].
Remove del for email
May 5 '07 #5
Please don't top-post. Put what you're replying below what you cite
from the previous post.

Ernst Schmidtmann <do*******@ulcu s.owl.dewrote:
1. Mhmm. If I allocate memory to a pointer, can I use this pointer
without defining an array?
You don't allocate "momory to a pointer", you allocate memory and
assign the address you receive from malloc() to a pointer. And
yes, of course, you can then use the pointer to access the
memory you allocated in an array-like fashion using the pointer.
I think, array is a pointer to the first element of the array.
Definitely not. An array is an array, not a pointer. Only when
the compiler finds an array in a place where a value is required
the array is replaced by a pointer to the first element of the
array. This happens e.g. when an array is used as a function
argument since in C all function arguments are passed by value
but an array isn't a value. And thus in this situation it gets
converted to a value, which is the address of its first element.
Memory
size from malloc and list[] is the same. Does the compiler have to
know the size of an element in the array?
If you create an array the compiler alreays knows the size
of the elements from the type of the array. But if you call
malloc() you need to tell malloc() exactly how much memory
you need, e.g. for enough memory to store 75 ints you do

int *ip;
ip = malloc( 75 * sizeof *ip );

where 'sizeof *ip' is the number of bytes required for the
type 'ip' points to, in this case the number of bytes needed
to store an int.
2. In the past I took integer arguments from the commandline by
defining argv[] as int. Well, there is a problem with argv[0], because
it is definitely the name of the program. But if I don't use it?
Then you did something wrong. The elements of argv are all
pointers to strings, pointing to strings with the command
line arguments (except argv[0] and the very last element,
which is always NULL). So if your first command line argu-
ment was 2 then argv[1] points to the string "2". And if
you now do

int max = *argv[1];

then you assign to 'max' the numerical value of the character
'2' and _not_ the integer value 2. And if the command line
argument had been 75 the argv[1] would point to the string
"75" and with the above assignment you would assign the
numerical value of the character '7' to 'max' and neither
the integer value 7 nor 75. You first have to convert the
string you got to an integer, using e.g. strtol().
3. I am not really sure, if I need a variable length array.
If you need memory with a size that only can be determined at
run-time and not already when the program gets compiled then
you either need a variable length array (which requires a com-
piler that implements at least this part of C99) or you must
obtain the memory via malloc().

Regards, Jens
--
\ Jens Thoms Toerring ___ jt@toerring.de
\______________ ____________ http://toerring.de
May 5 '07 #6
On May 5, 8:33 am, "virgincita schmidtmann" <doc.er...@t-online.de>
wrote:
>
int main(int argc, int *argv[]) {
This is an error. Not sure why nobody else noticed it;
perhaps they subconsciously filitered it out !

The second argument to main must have 'char' where
you current have 'int'. Who knows what your compiler
is doing with that code. Probably not what you expect!

May 6 '07 #7

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

Similar topics

8
3957
by: Alex Vinokur | last post by:
Various forms of argument passing ================================= C/C++ Performance Tests ======================= Using C/C++ Program Perfometer http://sourceforge.net/projects/cpp-perfometer http://alexvn.freeservers.com/s1/perfometer.html
3
14927
by: domeceo | last post by:
can anyone tell me why I cannot pass values in a setTimeout function whenever I use this function it says "menu is undefined" after th alert. function imgOff(menu, num) { if (document.images) { document.images.src = eval("mt" +menu+ ".src") } alert("imgOff_hidemenu"); hideMenu=setTimeout('Hide(menu,num)',500);
3
2862
by: Goh, Yong Kwang | last post by:
I'm trying to create a function that given a string, tokenize it and put into a dynamically-sized array of char* which is in turn also dynamically allocated based on the string token length. I call the function using this code fragement in my main function: --- char** arg_array; arg_count = create_arg_array(command, argument, arg_array); for(count = 0; count < arg_count; count++)
5
5824
by: jlea | last post by:
I'm trying to pass a filename, obtained with using the fileName property from the OpenFileDialog, as a application parameter in Process.StartInfo.Arguments and run a MFC/C++ application using the Start method. When I hardcode the application parameter such as "/name=c:\\myFile.txt" all is well in the C++ application. When I use the fileName property to build the parameter, the string becomes @"/name=c:\myFile.txt" which makes the C++...
2
4278
by: pyrexia | last post by:
Greets all. I'm attempting to write an app that will be used as a 'control/launcher' application for other apps. For the sake of argument let's say the app is launched from a command line: controlapp externalapp argument1 argument2 argument3 argument4...etc. (number of arguments is ALWAYS dynamic) I'm been able to get the array passed properly, but ONLY when I know in advance the amount of items in the array. I'm stuck on how to...
34
6849
by: Roman Mashak | last post by:
Hello, All! I'm implementing simple CLI (flat model, no tree-style menu etc.). Command line looks like this: <command> <param1> <param2> ... <paramN> (where N=1..4) And idea is pretty simple: 1) get whole string of input line 2) preset table of strings matching <command> 3) preset table of function calls
6
2353
by: =?Utf-8?B?Rm9ycmVzdCBIZWxsZXI=?= | last post by:
The only code that is helpful is this: fp = New IO.StreamReader(filename, New System.Text.UnicodeEncoding(True, False), False) If I pass a command line argument to my program that is not from Visual Studio.NET is debug mode, the above code won't work, even though filename is not changed whether I pass a command line argument or not. By not work, I mean it will set fp.EndOfStream to true and fp.Peek() returns -1. The command line argument...
2
4241
by: william.w.oneill | last post by:
I have an application that takes a few command line parameters. As recommended by others in this group, I'm using a named mutex to ensure that only one instance of the application is running. My question is how to elegantly pass a command line parameter from Instance_B to Instance_A where Instance_A was running prior to Instance_B. For example, the user can launch the program by passing a file name as a command line argument. The program...
4
7891
by: lilyumestar | last post by:
I have project I have to do for class. We have to write 4 different .java files. Project2.java HouseGUI.java House.java HouseSorting.java I already finish House.java and I need to work on both the Project2.java and HouseGUI.java Here are the requirements for those two. The GUI Create a class called HouseGUI which extends JFrame. It should display two text areas (JTextArea) in a grid layout (1 row, 2 columns). Your main program,...
0
8789
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
8693
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
8456
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
8570
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
6156
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
4279
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2694
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
1
1904
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1584
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.