Do I really need to zero arrays?

Discussion in 'C Programming' started by John Smith, Aug 19, 2005.

  1. John Smith

    John Smith Guest

    I have a two dimentional char array. Before filling it using
    strtok(), I reset its elements to '\0' using two nested for loops.
    The code works as I hope it would but I wonder whether I really
    need to reset the array. The program would run faster if I don't
    need to reset.

    ------------------------------------------
    int Array(void)

    .................
    for(i=0; i<ArrayNo; i++)
    for(j=0; j<ArraySize; j++)
    Arrays[j]='\0';


    pch = strtok (buffer,"\n");
    while (pch != NULL)
    {
    strcpy(Arrays[ii],pch);
    ii++;
    pch = strtok (NULL, "\n");
    }
    ...............
    ------------------------------------------
    John Smith, Aug 19, 2005
    #1
    1. Advertising

  2. John Smith wrote:
    > I have a two dimentional char array. Before filling it using
    > strtok(), I reset its elements to '\0' using two nested for
    > loops.
    > The code works as I hope it would but I wonder whether I really
    > need to reset the array. The program would run faster if I don't
    > need to reset.
    >
    > ------------------------------------------
    > int Array(void)
    >
    > ................
    > for(i=0; i<ArrayNo; i++)
    > for(j=0; j<ArraySize; j++)
    > Arrays[j]='\0';


    Your strcpy will properly copy the string (which by definition
    includes a null byte,) however any array elements that do not
    receive a string will have unspecified, assuming Arrays is a
    non-initialised block scope object.

    As an aside, you can zero initialise an object more easily...

    char Arrays[X][Y] = { { 0 } };

    With such a declaration, you could also use memset to re-
    initialise it...

    memset(Arrays, 0, sizeof Arrays);

    > pch = strtok (buffer,"\n");
    > while (pch != NULL)
    > {
    > strcpy(Arrays[ii],pch);


    You should be careful that there is actually space for the string
    in your arrays.

    > ii++;
    > pch = strtok (NULL, "\n");
    > }


    --
    Peter
    Peter Nilsson, Aug 19, 2005
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Zhiqiang Ye
    Replies:
    53
    Views:
    10,248
    Dan Pop
    Jun 28, 2004
  2. Gerard Flanagan
    Replies:
    3
    Views:
    443
    Terry Hancock
    Nov 19, 2005
  3. Christopher Benson-Manica

    Doubles and zero/negative zero

    Christopher Benson-Manica, Jun 30, 2004, in forum: C Programming
    Replies:
    4
    Views:
    674
    Walter
    Jul 1, 2004
  4. Replies:
    30
    Views:
    983
    Arne Vajhøj
    Feb 10, 2008
  5. Mahadev Ittina
    Replies:
    3
    Views:
    180
    Marnen Laibow-Koser
    Oct 31, 2009
Loading...

Share This Page