简体   繁体   中英

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.

static char *theValues[2];

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

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 eg

  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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM