C++ - char** argv vs. char* argv[]

C++MainArguments

C++ Problem Overview


What is the difference between char** argv and char* argv[]? in int main(int argc, char** argv) and int main(int argc, char* argv[])?

Are they the same? Especially that the first part does not have [].

C++ Solutions


Solution 1 - C++

They are entirely equivalent. char *argv[] must be read as array of pointers to char and an array argument is demoted to a pointer, so pointer to pointer to char, or char **.

This is the same in C.

Solution 2 - C++

They are indeed exactly the same.

The golden rule of arrays to remember is:

"The name of an array is a pointer to the first element of the array."

So if you declare the following:

char text[] = "A string of characters.";

Then the variable "text" is a pointer to the first char in the array of chars you've just declared. In other words, "text" is of type char *. When you access an element of an array using [index], what you're actually doing is adding an offset of index to the pointer to the first element of the array, and then dereferencing this new pointer. The following two lines will therefore initialize both variables to 't':

char thirdChar = text[3];
char thirdChar2 = *(text+3);

Using the square brackets is a convience provided by the language that makes the code much more readable. But the way this works is very important when you start thinking about more complex things, such as pointers to pointers. char** argv is the same as char* argv[] because in the second case "the name of the array is a pointer to the first element in the array".

From this you should also be able to see why it is that array indexes start from 0. The pointer to the first element is the array's variable name (golden rule again) plus an offset of... nothing!

I've had debates with a friend of mine as to which is better to use here. With the char* argv[] notation it may be clearer to the reader that this is in fact an "array of pointers to characters" as opposed to the char** argv notation which can be read as a "pointer to a pointer to a character". My opinion is that this latter notation doesn't convey as much information to the reader.

It's good to know that they're exactly the same, but for readablity I think that if the intention is an array of pointers then the char* argv[] notation conveys this much more clearly.

Solution 3 - C++

For all practical purposes, they're the same. This is due to C/C++'s handling of arrays passed as arguments, where an array decays to a pointer.

Solution 4 - C++

For the first part of the question:

  • char** argv: pointer to a pointer to a char
  • char* argv[]: pointer to an array

So the question is whether a pointer to a type C and an array C[] are the same things. They are not at all in general, BUT they are equivalent when used in signatures.

In other words, there is no difference in your example, but it is important to keep in mind the difference between pointer and array otherwise.

Solution 5 - C++

The bracket form is only useful in statement declarations like:

char *a[] = {"foo", "bar", "baz"};
printf("%d\n", sizeof a / sizeof *a);
// prints 3

Because it knows at compile time the size of the array. When you pass a bracket form as parameter to a function (main or some other one), the compiler has no idea what the size of the array would be at runtime, so it is exactly the same as char **a. I prefer char **argv since it's clearer that sizeof wouldn't work like it would on the statement declaration form.

Solution 6 - C++

This is a simple example I came up with, which have two functions (Main_1, Main_2) take the same arguments as the main function.

I hope this clear things up..

#include <iostream>

void Main_1(int argc, char **argv)
{
    for (int i = 0; i < argc; i++)
    {
        std::cout << *(argv + i) << std::endl;
    }
}

void Main_2(int argc, char *argv[])
{
    for (int i = 0; i < argc; i++)
    {
        std::cout << *(argv + i) << std::endl;
    }
}

int main()
{

    // character arrays with null terminators (0 or '\o')
    char arg1[] = {'h', 'e', 'l', 'l', 'o', 0};
    char arg2[] = {'h', 'o', 'w', 0};
    char arg3[] = {'a', 'r', 'e', '\0'};
    char arg4[] = {'y', 'o', 'u', '\n', '\0'};

    // arguments count
    int argc = 4;

    // array of char pointers (point to each character array (arg1, arg2, arg3 and arg4)
    char *argPtrs[] = {arg1, arg2, arg3, arg4};

    // pointer to char pointer array (argPtrs)
    char **argv = argPtrs;

    Main_1(argc, argv);
    Main_2(argc, argv);

    // or

    Main_1(argc, argPtrs);
    Main_2(argc, argPtrs);

    return 0;
}

Output :

hello
how
are
you

hello
how
are
you

hello
how
are
you

hello
how
are
you

Solution 7 - C++

There is a difference between TYPE * NAME and TYPE NAME[] in both C and C++. In C++ both types are not interchagneable. For example following function is illegal (you will get an error) in C++, but legal in C (you will get warning):

int some (int *a[3]) // a is array of dimension 3 of pointers to int
{
	return sizeof a;
}

int main ()
{
	int x[3][3];
	std::cout << some(x)<< std::endl;
	return 0;
}

To make it legal just change signature to int some (int (*a)[3]) (pointer to array of 3 ints) or int some (int a[][3]). The number in last square brackets must be equal to an argument's. Converting from array of arrays to an array of pointers is illegal. Converting from pointer to pointer to array of arrays is illegal too. But converting pointer to pointer to an array of pointers is legal!

So remember: Only nearest to dereference type signature doesn't matter, others do (in the context of pointers and arrays, sure).

Consider we have a as pointer to pointer to int:

int ** a;
&a     ->     a    ->    *a    ->    **a
(1)          (2)         (3)          (4)
  1. You cannot change this value, the type is int ***. May be taken by function as int **b[] or int ***b. The best is int *** const b.
  2. The type is int **. May be taken by function as int *b[] or int ** b. Brackets of the array declaratin may be leaved empty or contain any number.
  3. The type is int *. May be taken by function as int b[] or int * b or even void * b
  4. Should be taken as int parameter. I don't want to fall into details, like implicit constructor call.

Answering your question: the real type of argumets in main function is char ** argv, so it may be easily represented as char *argv[] (but not as char (*argv)[]). Also argv name of main function may be safely changed. You may check it easily: std::cout << typeid(argv).name(); (PPc = pointer to p. to char)

By the way: there is a cool feature, passing arrays as references:

void somef(int (&arr)[3])
{
    printf("%i", (sizeof arr)/(sizeof(int))); // will print 3!
}

Moreover pointer to anything may be implicitly accepted (converted) by function as void pointer. But only single pointer (not pointer to pointer etc.).

Further reading:

  1. Bjarne Stroustrup, C++, chapter 7.4
  2. C pointers FAQ

Solution 8 - C++

Both are same for your usage except for the following subtle differences:

  • Sizeof will give different results for both
  • Also second one may not be reassigned to new memory area since it's an array
  • With second one you can use only those indexes which are valid. It's unspecified by C/C++ if you try to use an array index beyond array length. However with char** you can use any index from 0 to ...
  • Second form can only be used as formal parameters to a function. While first can even be used to declare variables within a stack.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSimplicityView Question on Stackoverflow
Solution 1 - C++Fred FooView Answer on Stackoverflow
Solution 2 - C++James BedfordView Answer on Stackoverflow
Solution 3 - C++ErikView Answer on Stackoverflow
Solution 4 - C++David CournapeauView Answer on Stackoverflow
Solution 5 - C++JakeView Answer on Stackoverflow
Solution 6 - C++kavinda-ravishanView Answer on Stackoverflow
Solution 7 - C++yanpasView Answer on Stackoverflow
Solution 8 - C++user5858View Answer on Stackoverflow