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