Thread: Declare many Variables

  1. #1
    Registered User
    Join Date
    Aug 2013
    Posts
    6

    Declare many Variables

    Hello all:
    I have a question on how to declare multiple variables. For example, I need to declare the following:

    char imagekey1;
    char imagekey2;
    ....
    char imagekey50;

    Since it takes a long time to declare each (there are instances where I need to declare 600 different unique variables being used at one time), is there a easier way to do that (like looping...)?

  2. #2
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    An array, perhaps?

    Code:
    char imagekey[50];
    Or will they be of all different types/names (not like the example you showed)?

  3. #3
    Registered User
    Join Date
    Aug 2013
    Posts
    6
    "imagekey" part ramains the same. Its the number at the end that needs to change.

    char imagekey[50]; //My understanding is this just specifies the length, doesnt it?

  4. #4
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    This is an array of 50 chars.
    Code - functions and small libraries I use


    It’s 2014 and I still use printf() for debugging.


    "Programs must be written for people to read, and only incidentally for machines to execute. " —Harold Abelson

  5. #5
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    The array in my example actually declares fifty separate character variables. They can be accessed through the index, which is helpful for cycling through them in a loop, for instance.

    My understanding is this just specifies the length, doesnt it?
    Only in the context of a string - an array of characters terminated by a null character ('\0'). But again, it declares fifty separate character variables (theoretically in contiguous memory), each one a letter in the string.

    You can have arrays of any type:

    Code:
    int fruit[5] = {1,2,3,4,5};
    That line of code declares five separate integer variables, but in a way that they can be accessed easily in a loop. You cannot do the same with, say:

    Code:
    int apple = 1;
    int banana = 2;
    int peach = 3;
    int pear = 4;
    int coconut = 5;

  6. #6
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Say I want the char array to have every other letter. Easy to do with a loop:
    Code:
    char ch='a';
    int i = 0;
    char array[13]={' '}; //initialize all the array values to blank spaces
    while(ch <= 'z') {
       array[i]=ch;
       ch+=2;  //or ch=ch+2;
    }
    And you can make this much more sophisticated - say assigning only vowels to the array, etc. Your intuition was correct - you want to use the power of loops!

  7. #7
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    Quote Originally Posted by Adak View Post
    ...
    Code:
    char array[13]={' '}; //initialize all the array values to blank spaces
    I believe the standard dictates that when there are fewer initializers than elements, the rest of the elements are implicitly initialized to zero.

    That is why it "works out" if you initialize all elements to zero with " = {0}; ", but wouldn't hold true for other characters (e.g. space).
    Last edited by Matticus; 08-20-2013 at 03:47 PM.

  8. #8
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Quote Originally Posted by Matticus View Post
    I believe the standard dictates that when there are fewer initializers than elements, the rest of the elements are implicitly initialized to zero.

    That is why it "works out" if you initialize all elements to zero with "...", but wouldn't hold true for other characters (e.g. space).
    (Had to edit your post, the curly braces were screwing up the code tag checker -- know how to get around that?).

    You're correct:
    Quote Originally Posted by C99 6.7.8p21
    If there are fewer initializers in a brace-enclosed list than there are elements or members
    of an aggregate, or fewer characters in a string literal used to initialize an array of known
    size than there are elements in the array, the remainder of the aggregate shall be
    initialized implicitly the same as objects that have static storage duration.
    Note, the actual initialization is "the same as objects that have static storage duration", i.e. it will have the same value as a global or static local variable, with no initializer, of the same type. The rules for implicit initialization of static storage duration:
    Quote Originally Posted by C99 6.7.8p10
    If an object that has automatic storage duration is not initialized explicitly, its value is
    indeterminate. If an object that has static storage duration is not initialized explicitly,
    then:
    — if it has pointer type, it is initialized to a null pointer;
    — if it has arithmetic type, it is initialized to (positive or unsigned) zero;
    — if it is an aggregate, every member is initialized (recursively) according to these rules;
    — if it is a union, the first named member is initialized (recursively) according to these
    rules.

  9. #9
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    Thanks for providing the references, anduril462!

    (Had to edit your post, the curly braces were screwing up the code tag checker -- know how to get around that?).
    Yes - I don't see much harm in explaining it publicly, but will refrain from doing so to err on the side of caution. It's not that difficult, though.

  10. #10
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Quote Originally Posted by Matticus View Post
    Yes - I don't see much harm in explaining it publicly, but will refrain from doing so to err on the side of caution. It's not that difficult, though.
    Nor do I, since it would require as much extra effort to post code that subverts the code tag filter as it would to simply add code tags. But if you feel more comfortable, a PM would be just as good for me.

  11. #11
    Registered User
    Join Date
    Aug 2013
    Posts
    6
    Thanks for the reply Matticus. The applicaiton that I am working on is Loadrunner.
    This is how I approached for times where there were only 2 variables.

    Code:
    char imagekey1 [40];
    char imagekey2 [40];
    
    sprintf(imagekey1,"%s%s", lr_eval_string("{Bznext}"),lr_eval_string("0480099219"));   //Bznext is a parameter defined in an external file.
    sprintf(imagekey2,"%s%s", lr_eval_string("{Bznext}"),lr_eval_string("0480099220"));
    
     lr_output_message("%s", imagekey1);   //These do return a value
     lr_output_message("%s", imagekey2);
    Now I have 50 to 600 different variables that I need. From your advice, this is what I tried to do.

    Code:
    int i;
    char imagekey[50];
    
    for (i=1; i<=50; i++) 
     {
     
       sprintf(imagekey[i],"%s%s", lr_eval_string("{Bznext}"),lr_eval_string("0480099219"));     
       
       lr_output_message("%s", imagekey[i]);  // Returns a null value.
     }
    Thoughts??

  12. #12
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    Quote Originally Posted by Engineer1 View Post

    Code:
       lr_output_message("%s", imagekey[i]);  // Returns a null value.
    Thoughts??
    Either you need a better Compiler or you need to turn warnings on.
    Also, need to learn the difference between %c and %s in format strings.

    Tim S.
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

  13. #13
    Registered User
    Join Date
    Aug 2013
    Posts
    6
    The warning says "Invalid Parameter detected in function."

  14. #14
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    I think your terminology should be more clear. You are saying "variables" when it appears you mean "strings." A string is a collection (an array) of char variables, terminated with a null character ('\0');

    Code:
    char test[6] = "Hello";
    
    // The variable test[0] contains 'H'
    // The variable test[1] contains 'e'
    // The variable test[2] contains 'l'
    // The variable test[3] contains 'l'
    // The variable test[4] contains 'o'
    // The variable test[5] contains '\0'
    
    // The null character was automatically placed since we defined "test" with a
    // string literal.  That we why we need six elements; five for the letters in
    // "hello" and one for the null character
    Your first code defines two character arrays, each one used as a string of its own. You print a string to "imagekey1" (maximum of 40 characters, including '\0'). Then you print a string to "imagekey2" (also maximum of 40 characters, including '\0'). So you have two strings.

    In your second code, you have a single character array, which would equate to one string. If you wanted multiple strings, you would need to have a multidimensional array.

    Here's a brief illustrative example:

    Code:
    #include <stdio.h>
    
    #define NUM_WORDS  3
    #define WORD_LEN  16
    
    int main(void)
    {
        char test[NUM_WORDS][WORD_LEN] = {
            "string 1",
            "string 2",
            "string 3"
        };
        int i;
    
        for(i=0; i<NUM_WORDS; i++)
            printf("%s\n",test[i]);
    
        return 0;
    }

  15. #15
    Registered User
    Join Date
    Aug 2013
    Posts
    6
    Thanks for the explanation Matticus.
    So, If it was multidimensional array of 50, then, I would have to assign the values of each as you did eg: string 1, string 2, string 3... string 50?

    Is there a better way to approach this? Looping maybe .....

    Also, is there a way to parameterize the values, eg: instead of string 1---have a dynamic value?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help with declare
    By vandridel in forum C Programming
    Replies: 1
    Last Post: 03-06-2011, 02:30 AM
  2. Replies: 6
    Last Post: 12-02-2009, 08:47 AM
  3. Where to declare variables - Best Practise
    By darren78 in forum C++ Programming
    Replies: 1
    Last Post: 09-27-2009, 03:18 AM
  4. Replies: 3
    Last Post: 11-28-2006, 03:44 PM
  5. declare
    By shawn33 in forum C Programming
    Replies: 2
    Last Post: 12-12-2005, 02:48 PM

Tags for this Thread