execv in unix prob.

saravanan_'s Avatar, Join Date: Oct 2007
Go4Expert Member
Hi to all
Pls, help me in solving the problem execv() function.
My working environment is Solaris and solaris c compiler.
Can any one tell me how to use execv() function in c.
Following is the sample code:
main()
{
char a[][60]={"sample.sh", "one", "two", "three"};

execv("sample.sh", a);
}

but it gives error like "Bad Address"

Pls can any one help me out in this regard.
Thanks in advance
0
Salem's Avatar, Join Date: Nov 2007
Ambitious contributor
Because a should be an array of pointers, not an array of arrays.
Code:
char *a[] = { "sample.sh", "one", "two", "three", NULL };
0
saravanan_'s Avatar, Join Date: Oct 2007
Go4Expert Member
Thanks a lot Salem...........
Could you pls explain me what is the difference between char [][] and char *[].
0
Salem's Avatar, Join Date: Nov 2007
Ambitious contributor
The first is an array of arrays, the second is an array of pointers.

Compare the results of trying
strlen(a[0]) and sizeof(a[0]) for both ways of declaring the array.
0
saravanan_'s Avatar, Join Date: Oct 2007
Go4Expert Member
Thanks Salem.
I got your point.
But my question is that What is the problem to use the char [][] instead of char *[]
in the execv() system call.
Thanks in advance....
0
Salem's Avatar, Join Date: Nov 2007
Ambitious contributor
Well it expects an array of pointers, what more is there to understand?

They're not the same thing.
Code:
An array of arrays
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|H|E|L|L|O| |W|O|R|L|D| | | | | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|T|H|I|S| |W|O|R|K|S| | | | | | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|W|O|O|!| | | | | | | | | | | | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

An array of pointers
+----+    +-+-+-+-+-+-+-+-+-+-+-+-+
|    |--->|H|E|L|L|O| |W|O|R|L|D| |
+----+    +-+-+-+-+-+-+-+-+-+-+-+-+
|    |--->|T|H|I|S| |W|O|R|K|S| |
+----+    +-+-+-+-+-+-+-+-+-+-+-+
|    |--->|W|O|O|!| |
+----+    +-+-+-+-+-+
If you pass an array of arrays to something expecting an array of pointers, it's just going to take the first 4 characters of your string (say), and try and use that as a pointer to some other string. Then you immediately get something like unable to reference memory "0x41424344" where all the bytes of the "address" look remarkably like printable characters (in this case, ABCD).

Just because you can do
printf("%s", a[i] );
does NOT make them the same thing, because the compiler will generate slightly different code depending on how you declared the array to begin with.