Using memset for integer array in C

前端 未结 10 1693
遇见更好的自我
遇见更好的自我 2020-11-27 02:20
char str[] = \"beautiful earth\";
memset(str, \'*\', 6);
printf(\"%s\", str);

Output:
******ful earth

Like the above use of memset, can we initial

10条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-27 03:05

    Since nobody mentioned it...

    Although you cannot initialize the integers with value 1 using memset, you can initialize them with value -1 and simply change your logic to work with negative values instead.

    For example, to initialize the first 6 numbers of your array with -1, you would do

    memset(arr,-1,6*(sizeof int));
    

    Furthermore, if you only need to do this initialization once, you can actually declare the array to start with values 1 from compile time.

    int arr[15] = {1,1,1,1,1,1};
    

提交回复
热议问题