Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C Programming > Do I really need to zero arrays?

Reply
Thread Tools

Do I really need to zero arrays?

 
 
John Smith
Guest
Posts: n/a
 
      08-18-2005
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[i][j]='\0';


pch = strtok (buffer,"\n");
while (pch != NULL)
{
strcpy(Arrays[ii],pch);
ii++;
pch = strtok (NULL, "\n");
}
...............
------------------------------------------
 
Reply With Quote
 
 
 
 
Peter Nilsson
Guest
Posts: n/a
 
      08-18-2005
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[i][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

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
I really need help with this so if anyone can help me out that wouldbe really great of you. adityagaddam90@gmail.com Java 30 02-10-2008 11:29 PM
Can you set a class instance's attributes to zero by setting the instance to zero? Gerard Flanagan Python 3 11-19-2005 06:58 PM
do we really-really need Photoshop Elements? Giovanni Azua Digital Photography 6 05-18-2005 04:22 PM
Doubles and zero/negative zero Christopher Benson-Manica C Programming 4 07-01-2004 05:44 PM
memset all bits to zero will let float/double to zero? Zhiqiang Ye C Programming 53 06-28-2004 01:23 PM



Advertisments