views:

57

answers:

1

I got the following problem:

I have an array of char pointers

char *opts[] = { "-a", "--append", "-b" };

and a command name stored in

char cmd[] = "ls";

Now I need to compute all possible combinations, which I've done using the GNU Scientific Library and execute the command with the compute combinations.

The problem I have is how to compute the amount of memory I need for the char * getting passed to system().

Here's my first try:

int length = strlen(cmd) * sizeof(char);

for (int i = 0; i < 3; ++i) {
    length += strlen(opts[i]) * sizeof(char);
}

Well, it worked, but I sense that this is not the right/best solution. Can't I cast the two-dimensional-array to a flat one-dimensional-array and get the size of it (if I'm not wrong, the are no multidimensional arrays in C, C only mimics them).

+2  A: 

Can't I cast the two-dimensional-array to a flat one-dimensional-array

Technically not true, but irrelevant here, as you do not have a two-dimensional array. You have a 1-dimensional array of values which happen to have a length. There is no guarentee that those strings are in contiguous memory, so it would be impossible to measure their total sizze in one step.

The way to have it is the only way to get th evalue you want.

P.S. Note that sizeof(char) is guaranteed to equal 1.

P.P.S While I've already marked-down tommie75's answer, we can put part of it to use:

int numelem = sizeof(opts) / sizeof(opts[0]);
for (int i = 0; i < numelum; ++i) 
{ 
    length += strlen(opts[i]) * sizeof(char); 
} 
James Curran
James: Thanks! :) See my edited answer which pointed out a misleading title of the question...
tommieb75
Btw, I wouldn't guarantee that a sizeof(char) is equal to 1 either - that's implmentation defined as a result, on some systems it could be 2...http://stackoverflow.com/questions/2252033/in-c-why-is-sizeofchar-1-when-a-is-an-int
tommieb75
@tommieb75: The C standard says: `When [sizeof is] applied to an operand that has type char, unsigned char, or signed char,(or a qualified version thereof) the result is 1.`So sizeof ((un)?signed)? char *is* guaranteed to be 1, in standard C.
Tim Schaeffer
+1 Oh thanks, that was the point I totally got wrong. I thought the space would be contiguous.
Helper Method