Here’s my problem: I have an array, which contains a command a[1], followed by several command args a[2], a[3], …
What I need to do is the following
- Create a string, consisting of the cmd and a combination of args
E.g.:
cmd arg1 arg2 arg3
- Execute that command-string
Here’s how I woud do it (pseudo-code):
- Precompute the length of each arg and store it in an array
- Get a combination (using GNU Scientific Library)
- Compute the size in bytes needed to allocate the string (length of cmd + 1 +
lengthof arg1 + 1 + argn-1 + 1) (the +1 generally for the for the blank and at
the end for the \0) - Build the string by using strcat
- Execute the command-string
Well, it works but I wonder if using strcat that deliberately is actually efficient/the right way to do it.
Any suggestions?
No, using
strcat()is not efficient since it has to step through the string to find the end each time you call it.Much better to either do it all at once using
snprintf()if you have it (and can squeeze your arguments in there), or do it yourself using direct pointer manipulation.Of course, for this to matter in practice you need to be running this command very often indeed.