On 0, perceval anichini <anichi_p@epita.fr> wrote: > > correct, the call should be: > > execv( argv[1], argv[2] ); > > > For the fanatically correct, this might be better: > > execv( argv[1], argv + sizeof( argv[1] ) ); > > Could you explain this? Why would this line be *more* correct than the precedent? The second version makes the pointer arithmetic explicit and has the correct type for the second argument. The first involves an implicit cast from char* to char**. The type of argv is char**, an array of pointers to arrays of chars. The type of argv[2] is a pointer to an array of chars, *not* an array of pointers to arrays of chars, that is it is char*. But execv wants an array of arguments to pass to the executed main(...) function, so a cast takes place from char* to char**. Now it so happens that argv[2] is the beginning of an array pointers which is just argv with the first two items in it cut off, which is the array of arguments I want the pass to execv. I could make the cast explicit, but gcc is happy to do it implicitly, so I let it. > Moreover, argv + sizeof (argv[1]) is equal to argv[4] (as sizeof (char*) = 4) ... No. If that were so then you could not access the list of arguments to a main function as argv[0], argv[1], argv[2] etc. The compiler knows that the type of argv is char**, or char*[], an array of pointers to chars, and it knows that sizeof( char* ) is 4 (on the platforms we're talking about). It is almost an axiom that argv[1] == argv[0] + sizeof( argv[0] ), since this is the address of the next element in the array. So argv[4] = argv + 4*sizeof( argv[1] ). Would you believe it, I have made *another* mistake. That line should be: execv( argv[1], argv + 2*sizeof( argv[1] ) ); since I want argv[2] as the first element of the array which I am passing as second argument. Tom -- Tom Cook Information Technology Services, The University of Adelaide Classifications of inanimate objects: Those that don't work, those that break down, and those that get lost. Get my GPG public key: https://pinky.its.adelaide.edu.au/~tkcook/tom.cook-at-adelaide.edu.au
Attachment:
pgpEbe9Tw67gy.pgp
Description: PGP signature