Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

memset an array to 1

Tags:

c

I am trying to initialize a 2d array with some integer.If I initialize the array to 0 I am getting correct results but If I use some other integer I get some random values.

int main()
{
    int array[4][4];
    memset(array,1,sizeof(int)*16);
    printf("%d",array[1][2]); <---- Not set to 1
}
like image 504
user968000 Avatar asked Feb 07 '13 21:02

user968000


People also ask

Can we use memset for 1?

C++ Note: We can use memset() to set all values as 0 or -1 for integral data types also. It will not work if we use it to set as other values.

How do you do memset on an array?

memset() is used to fill a block of memory with a particular value. The syntax of memset() function is as follows : // ptr ==> Starting address of memory to be filled // x ==> Value to be filled // n ==> Number of bytes to be filled starting // from ptr to be filled void *memset(void *ptr, int x, size_t n);

Why does memset only work 0 and 1?

memset allows you to fill individual bytes as memory and you are trying to set integer values (maybe 4 or more bytes.) Your approach will only work on the number 0 and -1 as these are both represented in binary as 00000000 or 11111111 .

Is memset faster than a loop?

It depends. But, for sure memset is faster or equal to the for-loop. If you are uncertain of your environment or too lazy to test, take the safe route and go with memset. Please specify which one you mean by "above."


1 Answers

memset set every byte of your array to 1 not every int element.

Use an initializer list with all values set to 1 or a loop statement to copy a value of 1 to all the elements.

like image 120
ouah Avatar answered Oct 31 '22 22:10

ouah