Re: argv/pointer problems

From: Rolf Magnus (ramagnus_at_t-online.de)
Date: 06/16/04


Date: Wed, 16 Jun 2004 11:41:42 +0200

Robin Sanderson wrote:

> I have just noticed that I posted the wrong version of Programm 3 -
> the "** argv" should have been "* argv[]", and this is corrected below
> - although this does not alter whether or not it compiles.
>
> This may be a(nother) daft question, but what is it that makes the
> difference between the use of "char * argv[3]" in Program 2 and "char
> * argv[]" in Program 3?

In program 3, it's a parameter, while in program 2, it's a local
variable. You cannot pass arrays as parameters to functions, and
therefore, a "convenience" was added to C (and inherited to C++). If
you write a parameter in a form that looks like an array, it will
actually be a pointer. That's btw the reason why you can leave out the
size. When defining an array, you _always_ need a size for it.

> Is it possible to declare argv as a pointer in Program 2 (so it can be
> used in an identical way as in the other programs)?

int main()
{
    int i;

    int argc=3;
    char * args[3];

    args[0] = "program_name";
    args[1] = "argument_1";
    args[2] = "argument_2";

    char * (*argv) = args;
    // declares argv as a pointer to the array args

    for(i=0;i<argc;i++)
    {
        cout << "i="<<i<<"; *argv = " << *argv << endl;
        argv++;
    }

    return 0;
}



Relevant Pages

  • Re: Prime Numbers
    ... /*This code finally compiles as a 'c' code ... One more question....if i don't free up the memory allocated at the end ... it would appear that we are best served by an array ... prime numbers can be represented by an unsigned long int. ...
    (comp.lang.c)
  • Re: Newbie questions
    ... It compiles ... float getLowest(float array, int length); ... float getLowest(float array[], int length) { ... before printing a second prompt. ...
    (comp.lang.c)
  • Re: malloc and maximum size
    ... int main{ ... Change the array size to -1/2 and it compiles and prints ... same error message. ...
    (comp.lang.c)
  • Specifying global array size with const int
    ... int main ... Using the #define compiles with no errors, ... part of C to refuse to compile above code with a const int specifying ... array size, when the array is declared global? ...
    (comp.lang.c)
  • (patch for Bash) regex case statement
    ... Following up on my previous patch for regex conditional tests, ... /* Return an array of strings; ... int dollarflag, zeropad, compareflag; ... SHELL_VAR *var; ...
    (comp.unix.shell)