Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   execv in unix prob. (http://www.go4expert.com/forums/execv-unix-prob-t7546/)

saravanan_ 26Nov2007 12:31

execv in unix prob.
 
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

Salem 26Nov2007 17:23

Re: execv in unix prob.
 
Because a should be an array of pointers, not an array of arrays.
Code:

char *a[] = { "sample.sh", "one", "two", "three", NULL };

saravanan_ 28Nov2007 13:33

Re: execv in unix prob.
 
Thanks a lot Salem...........
Could you pls explain me what is the difference between char [][] and char *[].

Salem 28Nov2007 17:08

Re: execv in unix prob.
 
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.

saravanan_ 29Nov2007 15:57

Re: execv in unix prob.
 
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....

Salem 29Nov2007 17:17

Re: execv in unix prob.
 
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.


All times are GMT +5.5. The time now is 23:09.