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).

t0mm13b
  • 34,087
  • 8
  • 78
  • 110
helpermethod
  • 59,493
  • 71
  • 188
  • 276
  • since everything is in the end mapped to a unidimensional memory space, no language truly has multidimensional arrays... – fortran Feb 12 '10 at 16:03

1 Answers1

2

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
  • 101,701
  • 37
  • 181
  • 258
  • James: Thanks! :) See my edited answer which pointed out a misleading title of the question... – t0mm13b Feb 12 '10 at 14:50
  • 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 – t0mm13b Feb 12 '10 at 14:57
  • 1
    @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 Feb 12 '10 at 15:37
  • +1 Oh thanks, that was the point I totally got wrong. I thought the space would be contiguous. – helpermethod Feb 12 '10 at 18:31