-   Programming (
-   -   GTK tutorial question (

Abomb 05-10-2006 12:56 PM

GTK tutorial question
Hey guys,

I'm trying to teach myself some GTK. I'm currently on this:

Compiles fine but I don't get the desired response when I run the program.


$ ./packbox
usage: packbox num, where num is 1, 2, or 3.

I understand that it has something to do with this

if (argc != 2) {
  fprintf (stderr, "usage: packbox num, where num is 1, 2, or 3.\n");
  /* This just does cleanup in GTK and exits with an exit status of 1. */
  exit (1);

But I don't see where argc would be initialized to 2.

Thanks for any reply! Just a n00b trying to learn some programming. :)

paulsm4 05-10-2006 01:39 PM

Hi -

Every C or C++ program will have a function "main ()" that looks like this:

main (int argc, char *argv[])

There's one entry in the "char *argv[]" array for every command-line argument passed to your program (along with the pathname of your program itself, passed in as the first argument).

"int argc" is the number of cmd-line arguments. Argc will always be at least "1" (because the OS will always pass at least the name of your program).

In answer to your question "where does argc come from?" - the OS gives it to you when it begins executing your program.

Does that help?

Abomb 05-10-2006 04:17 PM

Hey, thanks for the reply.

Kinda make sense. How would do I get argc to 2? Not too sure I understand by what you mean when you say argc is the number of command line arguments.

Thanks for the help!

paulsm4 05-10-2006 05:33 PM

Hi -

Here's an example that might help:

1. Here's the program:

#include <stdio.h>

main (int argc, char *argv[])
  printf ("argc= %d...\n", argc);
  for (int i=0; i < argc; i++)
    printf ("argv[%d]= %s...\n", i, argv[i]);
  return 0;

2. Here's the build (sorry: my linux dev box isn't handy at the moment ;-):

C:\temp>cl hello.cpp
3. And finally, here's a sample run (with corresponding sample output):

C:\temp>hello a b c
argc= 4...
argv[0]= hello...
argv[1]= a...
argv[2]= b...
argv[3]= c...
4. Here's another example:

C:\temp>hello major kong
argc= 3...
argv[0]= hello...
argv[1]= major...
argv[2]= kong...
5. And yet another example:

C:\temp>cd \
C:\>c:\temp\hello dr. strangelove or how i learned to stop worrying and love the bomb
argc= 14...
argv[0]= c:\temp\hello...
argv[1]= dr....
argv[2]= strangelove...
argv[3]= or...
<< snipped >>
argv[12]= the...
argv[13]= bomb...
I hope that helps .. PSM

Abomb 05-10-2006 05:53 PM

Ahh! Got it! I'm still a n00b at programming, I'm not use to arguments in in main(). I'm just use to doing void main() {}.

Thanks for all your help!

All times are GMT -5. The time now is 08:47 PM.