Mr Aleph
Mr Aleph

Reputation: 1895

Initializing an array of strings with a value that is not constant

I have the following scenario:

char *value1 = decrypt(somestring);
char *value2 = decrypt(somethingelse);
static char *theValues[2] = {value1, value2};

This of course causes an error initializer is not a constant. the function decrypt() decrypts a value from the user's config file and returns a char*. I then have a for-loop that will check each value of theValues and compare it to a list of search strings.

If I remove the initialization and then try to copy value1 and value2 to theValues it crashes because I haven't allocated memory. I could go and malloc it and then copy the contents of value1, etc into the array, however I don't have 2 values like in the example above, I have 50.

Is there a way to initialize theValues without having to malloc each element on the array and manually copy the value after the decryption?

Thanks.

Upvotes: 0

Views: 119

Answers (2)

You could declare your array

  static char *theValues[2];

Then it has two null pointers, since it is static; and you can fill it with e.g.

  if (!thevalues[0]) 
      thevalues[0] = decrypt(somestring);
  if (!thevalues[1])
      thevalues[1] = decrypt(somethingelse);

The tests ensure that (assuming decrypt don't return a null pointer) the initialization happens once. When the same containing function is called again, only the tests are re-executed, not the initialization.

Upvotes: 1

Doug Currie
Doug Currie

Reputation: 41200

static char *theValues[2];

theValues[1] = decrypt(somestring);
theValues[2] = decrypt(somethingelse);

Upvotes: 1

Related Questions