0

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.

1
  • "If I remove the initialization and then try to copy value1 and value2 to theValues it crashes because I haven't allocated memory." Can you show us how you did this? This should work. Commented Dec 27, 2011 at 18:37

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That did it. I was trying to strcpy each one as opposed to copying the points. Great, thanks.
1
static char *theValues[2];

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.