Add items to an array

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Kevin Walzer

    Add items to an array

    I'm trying to generate an array of serial numbers for use in an
    application. I can get individual serial numbers printed to stdout using
    a for loop, but I cannot figure out how to append these numbers to an
    array.

    Here is my code:

    #include <stdio.h>

    int main (void) {

    int i;
    int count = 20000;
    char appname[] = "MYAPP";
    int serials[20000];
    for (i = 1; i < count; ++i) {
    int five = i*5;
    int eleven = i/11;
    int one = (i-1);
    printf("%s-%i-%i-%i\n", appname, five, eleven, one);
    }
    return 0;


    }

    In a higher-level language such as Python I'd do something like this:

    serialnumber = ("%s-%i-%i-%i\n", appname, five, eleven, one)
    serials.append( serialnumber)

    but I'm not sure how to assign this kind of value to a C variable, nor
    am I sure how to populate the C array with this value. Any advice is
    appreciated.

    --
    Kevin Walzer
    Code by Kevin

  • Richard

    #2
    Re: Add items to an array

    Kevin Walzer <kw@codebykevin .comwrites:
    I'm trying to generate an array of serial numbers for use in an
    application. I can get individual serial numbers printed to stdout
    using a for loop, but I cannot figure out how to append these numbers
    to an array.
    >
    Here is my code:
    >
    #include <stdio.h>
    >
    int main (void) {
    >
    int i;
    int count = 20000;
    char appname[] = "MYAPP";
    int serials[20000];
    Does that number look similar to anything else in the code? ....
    for (i = 1; i < count; ++i) {
    int five = i*5;
    int eleven = i/11;
    int one = (i-1);
    printf("%s-%i-%i-%i\n", appname, five, eleven, one);
    }
    Look at the start value of i. Read about indexing in C. Check the end
    case for the loop to be sure to be sure ....
    return 0;
    >
    >
    }
    >
    In a higher-level language such as Python I'd do something like this:
    >
    serialnumber = ("%s-%i-%i-%i\n", appname, five, eleven, one)
    serials.append( serialnumber)
    >
    but I'm not sure how to assign this kind of value to a C variable, nor
    am I sure how to populate the C array with this value. Any advice is
    appreciated.
    Look up sprintf.

    Comment

    • Default User

      #3
      Re: Add items to an array

      Kevin Walzer wrote:
      I'm trying to generate an array of serial numbers for use in an
      application. I can get individual serial numbers printed to stdout
      using a for loop, but I cannot figure out how to append these numbers
      to an array.
      char appname[] = "MYAPP";
      int serials[20000];
      In a higher-level language such as Python I'd do something like this:
      >
      serialnumber = ("%s-%i-%i-%i\n", appname, five, eleven, one)
      serials.append( serialnumber)
      The array serials[] is one containing ints. You have created strings
      with non-numeric components (like the app name). What exactly would you
      expect this append() to do? You certainly haven't created an int of any
      kind. You have a string. Why not an array of strings?




      Brian

      Comment

      • viza

        #4
        Re: Add items to an array

        On Mon, 23 Jun 2008 13:43:04 -0400, Kevin Walzer wrote:
        #include <stdio.h>
        >
        int main (void) {
        >
        int i;
        int count = 20000;
        char appname[] = "MYAPP";
        int serials[20000];
        You want an array of strings, so you need:

        char serials[2000][22];

        Here you should replace 22 with one more than the maximum size of your
        serial string. If you don't know that in advance, then you need to go
        away and learn dynamic memory allocation (start with man malloc). Some
        will say that having a 44kB automatic variable is a bad idea in any case,
        (and they would be right) so you should eventually learn how to allocate
        memory anyway.
        for (i = 1; i < count; ++i) {
        int five = i*5;
        int eleven = i/11;
        int one = (i-1);
        printf("%s-%i-%i-%i\n", appname, five, eleven, one);
        snprintf( serials[i], 22, "%s-%i-%i-%i\n",
        appname, five, eleven, one);

        You should also check that the return value of snprintf is less than 22,
        otherwise your string has been truncated by the fixed size buffer.
        }
        return 0;
        include <stdlib.hand use

        exit( EXIT_SUCCESS ); or exit( EXIT_FAILURE );
        }
        HTH

        viza

        Comment

        • vippstar@gmail.com

          #5
          Re: Add items to an array

          On Jun 23, 11:06 pm, viza <tom.v...@gmil. comwrote:
          On Mon, 23 Jun 2008 13:43:04 -0400, Kevin Walzer wrote:
          <snip>
          }
          return 0;
          >
          include <stdlib.hand use
          >
          exit( EXIT_SUCCESS ); or exit( EXIT_FAILURE );
          >
          }
          There isn't a problem with 'return 0', and there's a subtle difference
          between 'return' and exit(). Perhaps OP desires that?

          Comment

          • viza

            #6
            Re: Add items to an array

            On Mon, 23 Jun 2008 13:22:23 -0700, vippstar wrote:
            On Jun 23, 11:06 pm, viza <tom.v...@gmil. comwrote:
            >On Mon, 23 Jun 2008 13:43:04 -0400, Kevin Walzer wrote:
            <snip>
            }
            return 0;
            >>
            >include <stdlib.hand use
            >>
            > exit( EXIT_SUCCESS ); or exit( EXIT_FAILURE );
            >>
            }
            There isn't a problem with 'return 0', and there's a subtle difference
            between 'return' and exit(). Perhaps OP desires that?
            There isn't a problem with 'return EXIT_SUCCESS', but hard coding values
            (1) makes them difficult to find and change (2) ignores an opportunity to
            make the code easier to read.


            Comment

            • vippstar@gmail.com

              #7
              Re: Add items to an array

              On Jun 24, 12:30 am, viza <tom.v...@gmil. comwrote:
              On Mon, 23 Jun 2008 13:22:23 -0700, vippstar wrote:
              On Jun 23, 11:06 pm, viza <tom.v...@gmil. comwrote:
              On Mon, 23 Jun 2008 13:43:04 -0400, Kevin Walzer wrote:
              <snip>
              }
              return 0;
              >
              include <stdlib.hand use
              >
              exit( EXIT_SUCCESS ); or exit( EXIT_FAILURE );
              >
              }
              There isn't a problem with 'return 0', and there's a subtle difference
              between 'return' and exit(). Perhaps OP desires that?
              >
              There isn't a problem with 'return EXIT_SUCCESS', but hard coding values
              (1) makes them difficult to find and change (2) ignores an opportunity to
              make the code easier to read.
              '0' is not more or less of a hardcoded value than EXIT_SUCCESS in
              'return'

              Comment

              • Ali Karaali

                #8
                Re: Add items to an array

                '0' is not more or less of a hardcoded value than EXIT_SUCCESS in
                'return'- Alýntýyý gizle -
                >
                - Alýntýyý göster -

                in *more* system EXIT_SUCCESS = 0 and EXIT_FAILURE = 1. You are
                absolutely right.

                Comment

                • vippstar@gmail.com

                  #9
                  Re: Add items to an array

                  On Jun 24, 12:58 am, Ali Karaali <ali...@gmail.c omwrote:
                  '0' is not more or less of a hardcoded value than EXIT_SUCCESS in
                  'return'
                  in *more* system EXIT_SUCCESS = 0 and EXIT_FAILURE = 1. You are
                  absolutely right.
                  Actually the value of these two macros have nothing to do with 0 being
                  'hardcoded'.
                  I don't know what 'viza' is talking about, but 0 is not more or less
                  hardcoded than EXIT_SUCCESS/EXIT_FAILURE, regardless of the value of
                  the expressions the macros expand to.

                  Comment

                  • viza

                    #10
                    Re: Add items to an array

                    On Mon, 23 Jun 2008 15:02:19 -0700, vippstar wrote:
                    On Jun 24, 12:58 am, Ali Karaali <ali...@gmail.c omwrote:
                    >>On Mon, 23 Jun 2008 21:30:58 +0000, viza wrote:
                    >>>There isn't a problem with 'return EXIT_SUCCESS', but hard coding
                    >>>values (1) makes them difficult to find and change (2) ignores an
                    >>>opportunit y to make the code easier to read.
                    >>'0' is not more or less of a hardcoded value than EXIT_SUCCESS in
                    >>'return' in *more* system EXIT_SUCCESS = 0 and EXIT_FAILURE = 1.
                    Actually the value of these two macros have nothing to do with 0 being
                    'hardcoded'.
                    I don't know what 'viza' is talking about, but 0 is not more or less
                    hardcoded than EXIT_SUCCESS/EXIT_FAILURE, regardless of the value of the
                    expressions the macros expand to.
                    "Hard coded" wasn't the right term, but using literal constant values (as
                    opposed to a macro) is still a bad idea, because:

                    (1) it makes them difficult to find and change (eg when porting)

                    (2) it ignores an opportunity to make the code easier to read.

                    Only (2) is really significant here, but that is enough reason to use the
                    macro.

                    Comment

                    • Bartc

                      #11
                      Re: Add items to an array


                      "Kevin Walzer" <kw@codebykevin .comwrote in message
                      news:3f8bd$485f e02c$4275d90a$2 1110@FUSE.NET.. .
                      I'm trying to generate an array of serial numbers for use in an
                      application. I can get individual serial numbers printed to stdout using a
                      for loop, but I cannot figure out how to append these numbers to an array.
                      >
                      Here is my code:
                      >
                      #include <stdio.h>
                      >
                      int main (void) {
                      >
                      int i;
                      int count = 20000;
                      char appname[] = "MYAPP";
                      int serials[20000];
                      for (i = 1; i < count; ++i) {
                      int five = i*5;
                      int eleven = i/11;
                      int one = (i-1);
                      printf("%s-%i-%i-%i\n", appname, five, eleven, one);
                      }
                      return 0;
                      Any programming text will explain about arrays.

                      The C code should look more like this:

                      #include <stdio.h>
                      #include <stdlib.h>
                      #include <string.h>

                      #define count 20000

                      int main (void) {

                      int i,n;
                      char sno[100];
                      char appname[] = "MYAPP";
                      char *serials[count+1]; /* allow 1-based indexing */
                      char *p;

                      for (i = 1; i < count; ++i) {
                      int five = i*5;
                      int eleven = i/11;
                      int one = (i-1);

                      sprintf(sno,"%s-%i-%i-%i", appname, five, eleven, one);
                      n=strlen(sno);
                      p=malloc(n+1);
                      if (p==NULL) { puts("No more memory"); exit(0);}
                      strcpy(p,sno);
                      serials[i]=p;
                      }

                      for (i = 1; i < count; ++i)
                      printf("%d: %s\n",i,serials[i]);
                      return 0;
                      }

                      Each serial number string is allocated separately. You could simplify a bit
                      by allocating a fixed size (say 30 chars) per serial string. (If the serial
                      numbers are really generated like this, they don't need to be stored as a
                      string at all; just generated as needed by a function.)

                      In a higher-level language such as Python I'd do something like this:
                      >
                      serialnumber = ("%s-%i-%i-%i\n", appname, five, eleven, one)
                      Presumably there's something missing here?
                      serials.append( serialnumber)
                      So why are you switching to C?

                      -- Bartc



                      Comment

                      • Nick Keighley

                        #12
                        Re: Add items to an array

                        On 23 Jun, 23:02, vipps...@gmail. com wrote:
                        On Jun 24, 12:58 am, Ali Karaali <ali...@gmail.c omwrote:>
                        >'0' is not more or less of a hardcoded value than EXIT_SUCCESS in
                        'return'
                        I assume you meant "'0' is no more or less a hardcoded value than
                        EXIT_SUCCESS
                        in 'return".

                        I disagree.

                        in *more* system EXIT_SUCCESS = 0 and EXIT_FAILURE = 1. You are
                        absolutely right.
                        do you mean "most systems"?

                        I'm not being pedantic here, I'm simply not sure what you mean.

                        Actually the value of these two macros have nothing to do with 0 being
                        'hardcoded'.
                        I don't know what 'viza' is talking about, but 0 is not more or less
                        hardcoded than EXIT_SUCCESS/EXIT_FAILURE, regardless of the value of
                        the expressions the macros expand to.
                        Ok, so why do I disagree? There are a few reasons to hide hard-coded
                        values.

                        1. to document the code
                        2. to make the value easy to find and change
                        3. to make it different from other constants that take the same value,
                        at the moment.

                        most people think of 2 and hence regard "return 0" as perfectly clear.
                        It is also fine by rule 1. But may fall astray of rule 3.

                        How many zeros can there be in your code and can any of them change

                        NULL_POINTER, NUL_CHARACTER, INDEX_OFFSET, MONDAY

                        actually I was making those up. <pause for grep>

                        #define I_MIN_IDENT 0
                        #define xxx_NO_PID 0
                        #define LOG_EMERG 0
                        #define xxx_ALARMS_ALL_ CLEAR 0
                        #define xxx_LOCK_REST_O F_SEGMENT 0
                        #define MIN_STATUS_NO 0
                        #define DUMMY_ROW_NUMBE R 0
                        #define SACREDMEM 0
                        #define NO_CLIENT 0
                        #define xxx_SUCCESS 0
                        #define PARENT 0
                        #define NONE 0
                        #define NULL_OPPA 0
                        #define HEAD_OFFSET 0
                        #define TEST_INT_ZERO 0
                        #define HIGH_QUALITY 0
                        #define QUEUES_OFF 0

                        [only a sample (there were lots). Slightly edited to disguise source]

                        Can you (or I!) guarantee that *none* of those will ever change?


                        But also a confession. I regard zero (and 1) as slight exceptions.

                        I will write stuff like this:

                        /* remove '\n' */
                        str[nl_posn] = 0;

                        int main(void)
                        {
                        do_stuff();
                        return 0;
                        }

                        in C I use NULL. In C++ I use 0. It's a cultural thing.



                        --
                        Nick Keighley






                        Comment

                        • vippstar@gmail.com

                          #13
                          Re: Add items to an array

                          On Jun 24, 12:03 pm, Nick Keighley <nick_keighley_ nos...@hotmail. com>
                          wrote:
                          On 23 Jun, 23:02, vipps...@gmail. com wrote:
                          >
                          On Jun 24, 12:58 am, Ali Karaali <ali...@gmail.c omwrote:>
                          '0' is not more or less of a hardcoded value than EXIT_SUCCESS in
                          'return'
                          >
                          I assume you meant "'0' is no more or less a hardcoded value than
                          EXIT_SUCCESS
                          in 'return".
                          Yes, that is what I meant. I know my English isn't very good, but I
                          think I'm understandable with little effort :)
                          I disagree.
                          >
                          in *more* system EXIT_SUCCESS = 0 and EXIT_FAILURE = 1. You are
                          absolutely right.
                          >
                          do you mean "most systems"?
                          Just a note here: These are *not* my words, these are Mr Karaali's
                          words.
                          I'm not being pedantic here, I'm simply not sure what you mean.
                          >
                          Actually the value of these two macros have nothing to do with 0 being
                          'hardcoded'.
                          I don't know what 'viza' is talking about, but 0 is not more or less
                          hardcoded than EXIT_SUCCESS/EXIT_FAILURE, regardless of the value of
                          the expressions the macros expand to.
                          >
                          Ok, so why do I disagree? There are a few reasons to hide hard-coded
                          values.
                          Actually if you disagree you're wrong. Both EXIT_SUCCESS and 0 are
                          hardcoded values.
                          EXIT_SUCCESS offers nothing more over 0 whether you realize it or not.
                          It's not possible to redefine EXIT_SUCCESS to a value other
                          EXIT_SUCCESS or 0.
                          1. to document the code
                          2. to make the value easy to find and change
                          3. to make it different from other constants that take the same value,
                          at the moment.
                          >
                          most people think of 2 and hence regard "return 0" as perfectly clear.
                          It is also fine by rule 1. But may fall astray of rule 3.
                          >
                          How many zeros can there be in your code and can any of them change
                          >
                          NULL_POINTER, NUL_CHARACTER, INDEX_OFFSET, MONDAY
                          >
                          actually I was making those up. <pause for grep>
                          >
                          #define I_MIN_IDENT 0
                          #define xxx_NO_PID 0
                          #define LOG_EMERG 0
                          #define xxx_ALARMS_ALL_ CLEAR 0
                          #define xxx_LOCK_REST_O F_SEGMENT 0
                          #define MIN_STATUS_NO 0
                          #define DUMMY_ROW_NUMBE R 0
                          #define SACREDMEM 0
                          #define NO_CLIENT 0
                          #define xxx_SUCCESS 0
                          #define PARENT 0
                          #define NONE 0
                          #define NULL_OPPA 0
                          #define HEAD_OFFSET 0
                          #define TEST_INT_ZERO 0
                          #define HIGH_QUALITY 0
                          #define QUEUES_OFF 0
                          >
                          [only a sample (there were lots). Slightly edited to disguise source]
                          >
                          Can you (or I!) guarantee that *none* of those will ever change?
                          No, but I can guarantee EXIT_SUCCESS will not be redefined to a value
                          other than 0 or EXIT_SUCCESS.
                          But also a confession. I regard zero (and 1) as slight exceptions.
                          >
                          I will write stuff like this:
                          >
                          /* remove '\n' */
                          str[nl_posn] = 0;
                          >
                          int main(void)
                          {
                          do_stuff();
                          return 0;
                          >
                          }
                          >
                          in C I use NULL. In C++ I use 0. It's a cultural thing.
                          How is any of that relevant to EXIT_SUCCESS and 0 being both hardcoded
                          values?

                          Comment

                          • s0suk3@gmail.com

                            #14
                            Re: Add items to an array

                            On Jun 24, 6:00 am, vipps...@gmail. com wrote:
                            On Jun 24, 12:03 pm, Nick Keighley <nick_keighley_ nos...@hotmail. com>
                            wrote:On 23 Jun, 23:02, vipps...@gmail. com wrote:
                            >
                            On Jun 24, 12:58 am, Ali Karaali <ali...@gmail.c omwrote:>
                            >'0' is not more or less of a hardcoded value than EXIT_SUCCESS in
                            'return'
                            >
                            I assume you meant "'0' is no more or less a hardcoded value than
                            EXIT_SUCCESS
                            in 'return".
                            >
                            Yes, that is what I meant. I know my English isn't very good, but I
                            think I'm understandable with little effort :)I disagree.
                            >
                            in *more* system EXIT_SUCCESS = 0 and EXIT_FAILURE = 1. You are
                            absolutely right.
                            >
                            do you mean "most systems"?
                            >
                            Just a note here: These are *not* my words, these are Mr Karaali's
                            words.I'm not being pedantic here, I'm simply not sure what you mean.
                            >
                            Actually the value of these two macros have nothing to do with 0 being
                            'hardcoded'.
                            I don't know what 'viza' is talking about, but 0 is not more or less
                            hardcoded than EXIT_SUCCESS/EXIT_FAILURE, regardless of the value of
                            the expressions the macros expand to.
                            >
                            Ok, so why do I disagree? There are a few reasons to hide hard-coded
                            values.
                            >
                            Actually if you disagree you're wrong. Both EXIT_SUCCESS and 0 are
                            hardcoded values.
                            EXIT_SUCCESS offers nothing more over 0 whether you realize it or not.
                            It's not possible to redefine EXIT_SUCCESS to a value other
                            EXIT_SUCCESS or 0.
                            >
                            Yes, they're both hard-coded values. But EXIT_SUCCESS *does* offer
                            things that 0 doesn't: readability, self-documenting code, reusable
                            code, portability, among other things. Some of this points don't seem
                            so apparent in this particular case, plus 'return 0;' is almost like a
                            tradition. But in general, using macros rather than constants is
                            better in all senses. Otherwise, why would they have been invented in
                            the first place?

                            Comment

                            • santosh

                              #15
                              Re: Add items to an array

                              s0suk3@gmail.co m wrote:
                              On Jun 24, 6:00 am, vipps...@gmail. com wrote:
                              >Actually if you disagree you're wrong. Both EXIT_SUCCESS and 0 are
                              >hardcoded values. EXIT_SUCCESS offers nothing more over 0 whether you
                              >realize it or not. It's not possible to redefine EXIT_SUCCESS to a
                              >value other EXIT_SUCCESS or 0.
                              By not possible, I think you mean not portable, right?
                              Yes, they're both hard-coded values. But EXIT_SUCCESS *does* offer
                              things that 0 doesn't: readability,
                              Disputable. Literally every C programmer knows what a "return 0;" from
                              main means. It usually in one of the first chapters in every C book.
                              self-documenting code, reusable
                              code, portability, among other things.
                              And how is a literal zero return from main (or in an exit call) not
                              these?
                              Some of this points don't seem
                              so apparent in this particular case, plus 'return 0;' is almost like a
                              tradition. But in general, using macros rather than constants is
                              better in all senses. Otherwise, why would they have been invented in
                              the first place?
                              I think in this case EXIT_SUCCESS was created for symmetry rather than
                              any real need. But your general point of using macros instead of
                              literal constants where feasible is quite correct. I just don't think
                              that this case (0 or EXIT_SUCCESS) is a great example of illustrating
                              the advantages of macros. :-)

                              Comment

                              Working...