Do I really need to zero arrays?

J

John Smith

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");
}
...............
------------------------------------------
 
P

Peter Nilsson

John said:
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.
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top