LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   memset vs char arr initialization (https://www.linuxquestions.org/questions/programming-9/memset-vs-char-arr-initialization-429562/)

syseeker 03-29-2006 03:20 AM

memset vs char arr initialization
 
just a bit curious to ask...

given uint8_t block[25];

is

memset(block, '\0', 25);

equivalent to

for (i=0; i<25; i++)
block[i] = '\0';

?

stephenwalter 03-29-2006 03:29 AM

Hello,
There is one mistake though in what u hav typed. memset takes second argument as an integer so typically that has to be
memset(block,0,25);
Having said that , the behaviour is the same in both cases.

Regards,
S.Suresh Stephen.

syseeker 03-29-2006 04:07 AM

Arh.. ok, thanks for pointing that out, but why does glibc spec describes

void * memset (void *block, int c, size_t size) Function
This function copies the value of c (converted to an unsigned char) into each of the first size bytes of the object beginning at block. It returns the value of block.

stephenwalter 03-29-2006 04:31 AM

Hi,
The memset function will behave in such a manner after setting the value it would return a void pointer to that block which can be type casted into a char* , but take both arrays and check it up , both will have the same contents.

Regards,
S.Suresh Stephen

addy86 03-29-2006 09:01 AM

Quote:

Originally Posted by stephenwalter
Hello,
There is one mistake though in what u hav typed. memset takes second argument as an integer so typically that has to be
memset(block,0,25);

In C, it doesn't matter whether you write
memset(block,0,25);
or
memset(block,'\0',25);

memset vs. loop: The result is the same, but typically memset is highly tuned, so that it executes much faster for large buffers.


All times are GMT -5. The time now is 09:11 PM.